Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: JSON array

Tags:

json

delphi

Trying to understand the JSON in Delphi. Using the module "DBXJSON.pas". How to use it to make this such an array:

Array:[
        {"1":1_1,"1_2_1":1_2_2},
        ...,
   ]

Doing so:

JSONObject:=TJSONObject.Create;
JSONArray:=TJSONArray.Create();
...
JSONArray.AddElement(TJSONObject.Create(TJSONPair.Create('1','1_1')));
JSONArray.AddElement(TJSONObject.Create(TJSONPair.Create('1_2_1','1_2_2')));
JSONObject.AddPair('Array',JSONArray);

, but get this:

{
"Array":[
{"1":"1_1"},{"1_2_1":"1_2_2"}
]
}

Please help! Thanks!

like image 357
dedoki Avatar asked May 11 '12 10:05

dedoki


1 Answers

Code, wich you posted above, is not correct. You've created an JSON-Array and trying to add pair-elements to that array. But, instead of adding pairs to array you have to add JSON Objects to this array, and these objects have to contain your pairs.
here is an sample code to solve your problem:

program Project3;

{$APPTYPE CONSOLE}

uses
  SysUtils, dbxjson;

var jsobj, jso : TJsonObject;
    jsa : TJsonArray;
    jsp : TJsonPair;
begin
  try
    //create top-level object
    jsObj := TJsonObject.Create();
    //create an json-array
    jsa := TJsonArray.Create();
    //add array to object
    jsp := TJSONPair.Create('Array', jsa);
    jsObj.AddPair(jsp);

    //add items to the _first_ elemet of array
    jso := TJsonObject.Create();
    //add object pairs
    jso.AddPair(TJsonPair.Create('1', '1_1'));
    jso.AddPair(TJsonPair.Create('1_2_1', '1_2_2'));
    //put it into array
    jsa.AddElement(jso);

    //second element
    jso := TJsonObject.Create();
    //add object pairs
    jso.AddPair(TJsonPair.Create('x', 'x_x'));
    jso.AddPair(TJsonPair.Create('x_y_x', 'x_y_y'));
    //put it into array
    jsa.AddElement(jso);

    writeln(jsObj.ToString);
    readln;

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

and output is

{"Array":[
     {"1":"1_1","1_2_1":"1_2_2"},
     {"x":"x_x","x_y_x":"x_y_y"}
  ]
}
like image 117
teran Avatar answered Sep 24 '22 04:09

teran