How can I convert a JsonObject to a JSON String?

非 Y 不嫁゛ 提交于 2019-12-24 09:59:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!