Skip to content

Instantly share code, notes, and snippets.

@rich-wan
Forked from gamerxl/ue4-json-parsing.cpp
Created July 5, 2022 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rich-wan/b79fd204b0571509e80e26fb321e6425 to your computer and use it in GitHub Desktop.
Save rich-wan/b79fd204b0571509e80e26fb321e6425 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");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment