问题
I'm using Delphi 2010 and superobject library.
I have understand how to parse json-file, but I have no ideas how to create json?
The algorithm is:
- Parsing JSON and load in TStringGrid
- Adding data
- Save all TStringGrid data to json.
Need some example.
Thanks.
回答1:
Code sample to feed following structure to JSON object, then save to file:
(*
{
"name": "Henri Gourvest", /* this is a comment */
"vip": true,
"telephones": ["000000000", "111111111111"],
"age": 33,
"size": 1.83,
"addresses": [
{
"address": "blabla",
"city": "Metz",
"pc": 57000
},
{
"address": "blabla",
"city": "Nantes",
"pc": 44000
}
]
}
*)
procedure SaveJson;
var
json, json_sub: ISuperObject;
begin
json := SO;
json.S['name'] := 'Henri Gourvest';
json.B['vip'] := TRUE;
json.O['telephones'] := SA([]);
json.A['telephones'].S[0] := '000000000';
json.A['telephones'].S[1] := '111111111111';
json.I['age'] := 33;
json.D['size'] := 1.83;
json.O['addresses'] := SA([]);
json_sub := SO;
json_sub.S['address'] := 'blabla';
json_sub.S['city'] := 'Metz';
json_sub.I['pc'] := 57000;
json.A['addresses'].Add(json_sub);
json_sub.S['address'] := 'blabla';
json_sub.S['city'] := 'Nantes';
json_sub.I['pc'] := 44000;
json.A['addresses'].Add(json_sub);
json.SaveTo('C:\json_out.txt');
json := nil;
json_sub := nil;
end;
回答2:
Reading help file: https://github.com/hgourvest/superobject/blob/master/README.md
And then reading sources for TSuperArray ('Use the source, Luke')
Results in the following snippet:
var
obj: ISuperObject;
a: TSuperArray; // shortcut
begin
obj := TSuperObject.Create(stArray);
// or obj := SA([]);
a := obj.AsArray;
a.s[0] := 'aaaa';
a.s[1] := 'bbbb';
a.s[3] := 'cccc';
...
obj.SaveTo('File.txt');
a := nil; obj := nil;
...
end;
There is also the quote from help file: obj['foo[]'] := value; // add an item array
This suggests another way to populate an array (if the root object itself is not an array). Quoting http://code.google.com/p/superobject/source/browse/tests/test_usage.dpr
my_array := TSuperObject.Create(stArray);
my_array.I[''] := 1; // append
my_array.I[''] := 2; // append
my_array.I[''] := 3; // append
my_array.I['4'] := 5;
And later this object-array is inserted as property into yet another object
my_object := TSuperObject.Create(stObject);
my_object.I['abc'] := 12;
// my_object.S['path.to.foo[5]'] := 'bar';
my_object.B['bool0'] := false;
my_object.B['bool1'] := true;
my_object.S['baz'] := 'bang';
my_object.S['baz'] := 'fark';
my_object.AsObject.Delete('baz');
my_object['arr'] := my_array;
回答3:
A very good library for that is the LkJson: http://sourceforge.net/projects/lkjson/
To parse:
var jsText : String; jsObj : TlkJSONobject; begin
jsObj:=TlkJSON.ParseText(jsText) as TlkJSONobject;
To convert it back into text:
jsText := TlkJSON.GenerateText(jsObj);
来源:https://stackoverflow.com/questions/16790006/how-to-create-json-file-in-delphi-using-superobject-lib