UE4 C++ 把Json字符串读取为自定义的结构体

UE4 C++ 把Json字符串读取为自定义的结构体

需要解析的字符串

{
    "type": "UnrealEngine",
    "key": "sync_sc",
    "data": {
        "episode": "E01",
        "sc": "Sc01",
        "cam": "Cam001",
        "referenceAsset": {
            "character": [
                "zhangsan",
                "lisi",
                "wangwu"
            ],
            "props": [
                "Knife",
                "Gun"
            ]
        }
    }
}

1. 定义结构体

结构体变量名要和Json字符串的键对应起来

USTRUCT(BlueprintType)
struct Fsync_sc_data_referenceAsset
{
	GENERATED_BODY()
public:
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "DataStruct")
		TArray character;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "DataStruct")
		TArray props;
};

USTRUCT(BlueprintType)
struct Fsync_sc_data
{
	GENERATED_BODY()
public:
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "DataStruct")
		FString episode;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "DataStruct")
		FString sc;
	UPROPERTY(EditAnywhere, BluePrintReadWrite, Category = "DataStruct")
		FString cam;
	UPROPERTY(EditAnywhere, BluePrintReadWrite, Category = "DataStruct")
		Fsync_sc_data_referenceAsset referenceAsset;
};

USTRUCT(BlueprintType)
struct Fsync_sc
{
	GENERATED_BODY()
public:
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "DataStruct")
		FString type;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "DataStruct")
		FString key;
	UPROPERTY(EditAnywhere, BluePrintReadWrite, Category = "DataStruct")
		Fsync_sc_data data;
};

2.C++解析Json

FString JsonString = "{\"type\":\"UnrealEngine\",\"key\":\"sync_sc\",\"data\":{\"episode\":\"E01\",\"sc\":\"Sc01\",\"cam\":\"Cam001\",\"referenceAsset\":{\"character\":[\"zhangsan\",\"lisi\",\"wangwu\"],\"props\":[\"Knife\",\"Gun\"]}}}";
//1. 把字符串解析为JsonObject
TSharedPtr JsonObject;
TSharedRef> Reader = TJsonReaderFactory<>::Create(JsonString);
bool bIsOk = FJsonSerializer::Deserialize(Reader, JsonObject);
if (!bIsOk) {
	UE_LOG(LogTemp, Log, TEXT("Deserialize has Error!"));
}
//2. 把JsonObject转化为自定义结构体
Fsync_sc jsonData;
FJsonObjectConverter::JsonObjectToUStruct(JsonObject.ToSharedRef(), Fsync_sc::StaticStruct(), &jsonData, 1, 0);
UE_LOG(LogTemp, Log, TEXT("cam is %s"), *jsonData.data.cam);

UE4 C++ 把Json字符串读取为自定义的结构体_第1张图片

你可能感兴趣的:(UE4,unreal,json,c++)