问题
I'm trying to convert a struct and the data it contains into a legitimate JSON String. I work in Unreal Engine in C++.
Struct I'm trying to convert:
USTRUCT()
struct DATALOGGING_API FGURaaSDataStruct
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY()
FString id_session = "test";
UPROPERTY()
TArray<FData> data;
};
Struct that is used in the previous struct:
USTRUCT()
struct DATALOGGING_API FData
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY()
FString data;
UPROPERTY()
FString tag1;
UPROPERTY()
FString tag2;
UPROPERTY()
FString tag3;
UPROPERTY()
FString tag4;
UPROPERTY()
TArray<FString> additional_tags;
UPROPERTY()
FString time;
};
Current aproach: (JsonObject - UE4 specific code)
FGURaaSDataStruct tObj = FGURaaSDataStruct();
TSharedPtr<FJsonObject> jsonObject = FJsonObjectConverter::UStructToJsonObject<FGURaaSDataStruct>(tObj);
The JsonObject generated here contains all the information necessary to create a Json String, ideally I would like to have a simple way to convert this JsonObject into an JSON String.
回答1:
This will serialize the Json to OutputString which you are then free to do whatever you want.
For more information, see Using Json in Unreal Engine 4.
void FStructToJsonString(FStructXXX _myStruct) {
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
JsonObject->SetStringField("param1", _myStruct.param1);
JsonObject->SetStringField("param2", _myStruct.param2);
FString OutputString;
TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);
FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer);
UE_LOG(LogTemp, Warning, TEXT("resulting jsonString -> %s"), *OutputString);
}
来源:https://stackoverflow.com/questions/48189024/how-can-i-convert-a-jsonobject-to-a-json-string