Delphi: JSON array

24,716

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"}
  ]
}
Share:
24,716
dedoki
Author by

dedoki

Updated on October 19, 2020

Comments

  • dedoki
    dedoki over 3 years

    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!