Download

Best Way to Handle JSON

Hi,

I’m quite new to c++ in Unreal 4 and I’m currently getting JSON trough REST. I have the response from server but the problem is to go get values properly from json. One thing which confuses me is JsonObject. So how to initialize it properly? How can I set my JSON response to JsonObject and how to get values out of it?

I’m trying out something like this.



		MessageBody = Response->GetContentAsString();
		
		TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
		TSharedRef< TJsonReader<> > JsonReader = TJsonReaderFactory<>::Create(*MessageBody);

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

		TArray<TSharedPtr<FJsonValue>> objArray = JsonObject->GetArrayField(TEXT("rows"));

		for (int32 i = 0; i < objArray.Num(); i++)
		{
			TSharedPtr<FJsonValue> value = objArray*;
			TSharedPtr<FJsonObject> json = value->AsObject();

			FString name = json->GetStringField(TEXT("51205"));
			
		}


You can check GitHub - ufna/VaRest: REST API plugin for Unreal Engine 4 - we love restfull backend and JSON communications!

Awesome! I’ll check that out.

Ok I sat down and took a deep breath. I got the value I was looking for.



		MessageBody = Response->GetContentAsString();
		TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
		TSharedRef< TJsonReader<> > JsonReader = TJsonReaderFactory<>::Create(MessageBody);

		// Deserialize the JSON data

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

			TSharedPtr<FJsonObject> jsonObj = JsonObject->GetObjectField("table");
			TArray<TSharedPtr<FJsonValue>> objArray = jsonObj->GetArrayField("rows");

			for (int32 i = 0; i < objArray.Num(); i++)
			{
	
				TArray<TSharedPtr<FJsonValue>> height = objArray*->AsArray();
				FString name = height[2]->AsString();
								
				UE_LOG(LogTemp, Warning, TEXT("Value I'm looking for %s"), *name);

			}
		}


JSON:



{
    "table": {
        "columnNames": 
            "actor",
            "height"
        ],
        "columnTypes": 
            "String",
            "float"
        ],
        "columnUnits": 
            null,
            "m"
        ],
        "rows": 
            
                "11111",
                2.5
            ],
            
                "11111",
                2.4
            ]
        ]
    }
}