Array json parsing

Hello,
I have a json structured with several arrays imbricated.

I ve started such code, but I don’t know how to manage the second level of arrays

Can you help, plz to fill my code?

if (FJsonSerializer::Deserialize(JsonReader, JsonParsed))
	{
		UE_LOG(ShimLog, Warning, TEXT("JSON OK"));
		TArray <TSharedPtr<FJsonValue>> zonesJs =  JsonParsed->GetArrayField("Zones");
		for (int itZones = 0; itZones != zonesJs.Num(); itZones++) {
			/// zonesJs[itZones]-> ???? // how to retrieve id?
                        /// zonesJs[itZones]-> ???? // how to array of events?


		}
	}




{
  "zones" :[
    {
      "id" : 1,
      "events":[
        {
          "id" : 1,
          "name" : "petitpirate",
          "relatedmission" : 1,
          "possibility" : 80,
          "reproduceEvenMissionFinished" : false,
          "spawn" : {
            "ship" : "darkfighter",
            "position" : "5000,5000,5000",
            "nbship" : 1
          }
        }
      ]
    }
  ]
}

Here my code, and it works.

FString projectDir = FPaths::GameDir();
	projectDir += "/Content/data/events.json";
	//

	if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*projectDir))
	{
		UE_LOG(ShimLog, Warning, TEXT("FILE NOT FOUND %s"), *projectDir);
		return;
	}
	FString FileData = "TEST";
	FFileHelper::LoadFileToString(FileData, *projectDir);
	TSharedPtr<FJsonObject> JsonParsed;

	TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(FileData);

	if (FJsonSerializer::Deserialize(JsonReader, JsonParsed))
	{
		TArray <TSharedPtr<FJsonValue>> zonesJs =  JsonParsed->GetArrayField("Zones");
		for (int itZones = 0; itZones != zonesJs.Num(); itZones++) {
			TSharedPtr<FJsonObject> temp = zonesJs[itZones]->AsObject();
			TArray <TSharedPtr<FJsonValue>> eventJs = temp->GetArrayField("events");
			for (int itEvents = 0; itEvents != eventJs.Num(); itEvents++) {
				TSharedPtr<FJsonObject> tempEventJs = eventJs[itEvents]->AsObject();
				FString nameEvents = tempEventJs->GetStringField("name");
	
			}

		}
	}
	else {
		UE_LOG(ShimLog, Warning, TEXT("JSON KO"));
	}

It solved my problem, thank you very much!

Your case can be automize by using this - json2ue4.com. This tool generate ustructs, which understand nested structures, arrays and common types like FString, int32, bool and float. Also it can generate serialization from json string. And you can easy work with your data. Enjoy.

In UE5 (at least) there’s now JsonArrayToUStruct (Thanks so much Epic!)

So all you need now is this:

// leave the code above
TArray<UMyStruct> data;
bool success = FJsonSerializer::Deserialize(JsonReader, JsonParsed) &&  FJsonObjectConverter::JsonArrayToUStruct(JsonParsed->AsArray(), &data);

also on UE5 FPaths::GameDir is now FPaths::ProjectContentDir() afaik.

But “FJsonObject” don’t have method “AsArray()” :frowning:

it’s not FJsonObject it’s FJsonValue
also it’s at least ue5, not sure if it’s on ue4 maybe 4.27

1 Like