How to parse Array of Array in a JSON file in C++ using Unreal

Deadly 提交于 2019-12-24 08:06:59

问题


The following is the JSON file I am trying to parse:-

{  
   "GameSetting":{  
      "Num_Levels":"3",
      "Env_Type":"Indoor"
   },
   "Indoor":[  
      {  
         "Name":"simple room",
         "objects":[  
            {"objectName":"chair"},
            {"objectName":"tables"},
            {"objectName":"boxes"},
            {"objectName":"barrels"}
         ],
         "number_of_objects":"10"
      },
      {  
         "Name":"multistory",
         "objects":[  
           { "objectName":"chair"},
            {"objectName":"tables"},
            {"objectName":"railings"},
            {"objectName":"staircase"}
         ],
         "number_of_objects":"25"
      },
      {  
         "Name":"passageway",
         "objects":[  
            {"objectName":"forklift"},
            {"objectName":"tables"},
            {"objectName":"rooms"},
            {"objectName":"doors"}
         ],
         "number_of_objects":"32"
      }
   ],
   "Outdoor":[  
      {  
         "Name":"Downtown",
         "objects":[  
            {"objectName":"Tall buildings"},
            {"objectName":"medium buildings"},
            {"objectName":"cars"},
            {"objectName":"people"}
         ],
         "number_of_objects":"10",
         "Weather":"sunny",
         "Wind":"Yes"
      },
      {  
         "Name":"Neighborhood",
         "objects":[  
            {"objectName":"houses"},
            {"objectName":"complexes"},
            {"objectName":"community area"},
            {"objectName":"park"},
            {"objectName":"cars"},
            {"objectName":"people"}
         ],
         "number_of_objects":"25",
         "Weather":"rainy",
         "Wind":"Yes"
      },
      {  
         "Name":"Forest",
         "objects":[  
            {"objectName":"trees"},
            {"objectName":"lake"},
            {"objectName":"mountains"}
         ],
         "number_of_objects":"32",
     "Weather":"rainy",
         "Wind":"No"
      }
   ]
}

I am using the approach specified in the answer of this question: C++ Nested JSON in Unreal Engine 4

I am successfully able to access GameSetting's both properties, Indoor's Name and number_of_objects properties and Outdoor's Name, number_of_objects, Wind and Weather properties. The only property I am having trouble with is the object arrays in both Indoor and Outdoor.

The following is my header file:

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "JsonParser.generated.h"

USTRUCT()
struct FGameSetting
{
    GENERATED_USTRUCT_BODY()

        UPROPERTY()
        FString Num_Levels;

    UPROPERTY()
        FString Env_Type;
};
USTRUCT()
struct FArrayBasic
{
    GENERATED_USTRUCT_BODY()

        UPROPERTY()
        FString objectName;
};
USTRUCT()
struct FIndoorBasic
{
    GENERATED_USTRUCT_BODY()

        UPROPERTY()
        FString Name;

        TArray <FArrayBasic> objects;

        UPROPERTY()
        FString number_of_objects;
};
USTRUCT()
struct FOutDoorBasic
{
    GENERATED_USTRUCT_BODY()

        UPROPERTY()
        FString Name;

    TArray <FArrayBasic> objects;

    UPROPERTY()
        FString number_of_objects;

    UPROPERTY()
        FString Weather;

    UPROPERTY()
        FString Wind;
};
USTRUCT()
struct FMain
{
    GENERATED_USTRUCT_BODY()

        UPROPERTY()
        FGameSetting GameSetting;

    UPROPERTY()
        TArray<FIndoorBasic>Indoor;

    UPROPERTY()
        TArray<FOutDoorBasic>Outdoor;

};

UCLASS()
class JSONPARSING_API AJsonParser : public AActor
{
    GENERATED_BODY()

public: 
    // Sets default values for this actor's properties
    AJsonParser();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;


public: 
    // Called every frame
    virtual void Tick(float DeltaTime) override;



};

and .cpp file:

// Fill out your copyright notice in the Description page of Project Settings.

#include "JsonParser.h"
#include "JsonUtilities.h"

// Sets default values
AJsonParser::AJsonParser()
{
    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void AJsonParser::BeginPlay()
{
    Super::BeginPlay();

    const FString JsonFilePath = FPaths::ProjectContentDir() + "/JsonFiles/randomgenerated.json";
    FString JsonString; //Json converted to FString

    FFileHelper::LoadFileToString(JsonString,*JsonFilePath);


    //Displaying the json in a string format inside the output log
    GLog->Log("Json String:");
    GLog->Log(JsonString);

    //Create a json object to store the information from the json string
    //The json reader is used to deserialize the json object later on
    TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
    TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(JsonString);

    if (FJsonSerializer::Deserialize(JsonReader, JsonObject) && JsonObject.IsValid())
    {

        FMain Main;
        FJsonObjectConverter::JsonObjectStringToUStruct<FMain>(JsonString, &Main, 0, 0);

        FString Data = Main.Outdoor[0].Wind;
        //FArrayBasic Data1 = Main.Indoor[0].objects.GetData[0];
        GLog->Log("sfdjngejbfwjqwnoesfjkesngkwbegjkwefbnjk");
        GLog->Log(Data);


        //for (int32 index = 0; index<Data.Num(); index++)
        //{
        //  GLog->Log("name:" + Data[index]->AsString());
        //}


        //The person "object" that is retrieved from the given json file
        TSharedPtr<FJsonObject> GameSetting = JsonObject->GetObjectField("GameSetting");

        //Getting various properties
        GLog->Log("ENV_TYPE:" + GameSetting->GetStringField("ENV_TYPE"));
        GLog->Log("NUM_LEVELS:" + FString::FromInt(GameSetting->GetIntegerField("NUM_LEVELS")));

        //Retrieving an array property and printing each field
        /*TArray<TSharedPtr<FJsonValue>> objArray=PersonObject->GetArrayField("family");
        GLog->Log("printing family names...");
        for(int32 index=0;index<objArray.Num();index++)
        {

            GLog->Log("name:"+objArray[index]->AsString());
        }*/
    }
    else
    {
        GLog->Log("couldn't deserialize");
    }

}

// Called every frame
void AJsonParser::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

}

It would be extremely helpful if anyone can help me parse the array within the array in the JSON file using the same methodology. Thanks in advance.


回答1:


Figured it out.

I just have to make the TArray < FArrayBasic > objects a UPROPERTY() for it to reflect in this system and get the values copied to it so that we can access it how I am trying to access it.



来源:https://stackoverflow.com/questions/52516942/how-to-parse-array-of-array-in-a-json-file-in-c-using-unreal

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