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