Page 1 of 1

Parse json

PostPosted: Fri Jun 02, 2017 8:29 am
by ingalime
Hello.
In this forum I found info how parse json:
Code: Select all
   std::unique_ptr<TJSONValue> LJSONValue(TJSONObject::ParseJSONValue(rezult));
   TJSONObject *LJSONObject = dynamic_cast<TJSONObject*>(LJSONValue.get());
   if(LJSONObject != NULL)
    {
     TJSONPair * JSONPair;
     String JsonMemberName;
     String JsonMemberValue;
     String Message = "";//for ShowMessage
     for (int i = 0; i < LJSONObject->Count; i++)
      {
       JSONPair = LJSONObject->Pairs[i];
       if(JSONPair != NULL)
         {
          JsonMemberName = JSONPair->JsonString->Value();
          JsonMemberValue = JSONPair->JsonValue->ToString();
//****

But I don't understand how parse json when json object contains an internal json object:
How parse?
Code: Select all
 {
    "status": "OK",
   "struct": {
      "full": 2,
        "success": 1
    }
 }


I want get ShowMessage with such content:
status: "OK",
full: 2,
success: 1


How right?

Re: Parse json

PostPosted: Fri Jun 02, 2017 12:23 pm
by rlebeau
ingalime wrote:But I don't understand how parse json when json object contains an internal json object


What don't you understand about it exactly? Have you read the JSON spec yet? Have you read Embarcadero's documentation yet?

In Embarcadero's JSON framework, all JSON values derive from TJSONValue. For a nested object, a value will be a TJSONObject, so simply type-cast.

ingalime wrote:How parse?
Code: Select all
 {
    "status": "OK",
   "struct": {
      "full": 2,
        "success": 1
    }
 }


I want get ShowMessage with such content:
status: "OK",
full: 2,
success: 1



Try this:

Code: Select all
#include <System.JSON.hpp>
#include <memory>

String json  = ...;

std::unique_ptr<TJSONValue> LJSONValue(TJSONObject::ParseJSONValue(json));

TJSONObject *LJSONObject = static_cast<TJSONObject*>(LJSONValue.get());
String Status = LJSONObject->Values["status"]->Value();

LJSONObject = static_cast<TJSONObject*>(LJSONObject->Values["struct"]);
int Full = static_cast<TJSONNumber*>(LJSONObject->Values["full"])->AsInt;
int Success = static_cast<TJSONNumber*>(LJSONObject->Values["success"])->AsInt;

String msg = Format(_D("status: \"%s\"\nfull: %d\nsuccess: %d"), ARRAYOFCONST(( Status, Full, Success )) );
ShowMesssage(msg);

Re: Parse json

PostPosted: Sat Jun 03, 2017 7:53 am
by ingalime
Thank you all from the heart!