UStruct定义:
USTRUCT()
struct FHeartBeatMsg
{GENERATED_BODY()
public:UPROPERTY()FString pcCode = TEXT("");UPROPERTY()FString deviceType = TEXT("");UPROPERTY()FString messageType = TEXT("");UPROPERTY()FString content = TEXT("");
};
使用相应转换函数需要添加相关插件模块,Json、JsonUtilities:
PrivateDependencyModuleNames.AddRange(new string[]{"CoreUObject","Engine","Json","JsonUtilities"});
相关头文件引入:
#include "JsonObjectConverter.h"
一、json转换为struct
1、json字符串转换为struct
//FString JsonStrFHeartBeatMsg sRecMsg;FJsonObjectConverter::JsonObjectStringToUStruct<FHeartBeatMsg>(JsonStr, &sRecMsg, 0, 0);
2、json object转换为struct
FHeartBeatMsg sRecMsg;FJsonObjectConverter::JsonObjectToUStruct<FHeartBeatMsg>(RootObj.ToSharedRef(), &sRecMsg, 0, 0);
附加:json字符串转json object
//FString JsonStrTSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(JsonStr);TSharedPtr<FJsonObject> RootObj = MakeShareable(new FJsonObject);if (!FJsonSerializer::Deserialize(JsonReader, RootObj)){return;}
二、struct转换为json字符串
FHeartBeatMsg sHeartBeatMsg;sHeartBeatMsg.pcCode = TEXT("123");sHeartBeatMsg.content = TEXT("test");;FString ContentJsonString;bool bRet = FJsonObjectConverter::UStructToJsonObjectString(FHeartBeatMsg::StaticStruct(), &sHeartBeatMsg, ContentJsonString, 0, 0);if (!bRet){//UE_LOGreturn;}
注意字符串大小写