Skip to content

Instantly share code, notes, and snippets.

@gamerxl
Last active January 13, 2024 11:49
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save gamerxl/6c8f4426866c82f7327d063343d02fe9 to your computer and use it in GitHub Desktop.
Save gamerxl/6c8f4426866c82f7327d063343d02fe9 to your computer and use it in GitHub Desktop.
How to parse a json response (e.g. a json array) in ue4 c++ context.
/**
* Include the PrivateDependencyModuleNames entries below in your project build target configuration:
* PrivateDependencyModuleNames.AddRange(new string[] { "Json", "JsonUtilities" });
*/
#include "Runtime/Online/HTTP/Public/Http.h"
#include "Serialization/JsonSerializer.h"
FHttpResponsePtr Response;
{
// Single json value (any of supported json types e.g.
// object with properties, array, bool) at top level of json
TSharedPtr<FJsonValue> JsonValue;
// Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
// Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonValue)) {
// Get the value of the json object by field name
bool status = JsonValue->AsObject()->GetBoolField("status");
}
}
{
// Array of json objects at top level of json
TSharedPtr<FJsonObject> JsonObject;
// Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
// Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject)) {
// Get the value of the json object by field name
FString name = JsonObject->GetStringField("name");
}
}
{
// Array of json objects at top level of json
TArray<TSharedPtr<FJsonValue>> JsonArray;
// Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
// Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonArray)) {
//Get the value of the json object by field name
FString name = JsonArray[0]->AsObject()->GetStringField("name");
}
}
@Saufian
Copy link

Saufian commented May 12, 2021

Thank you very much for this example of json array parsing.

It inspired me, and you saved my day with this.

@rhiskey
Copy link

rhiskey commented Jul 13, 2023

Thank you too!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment