9

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:

  1. Parsing JSON and load in TStringGrid
  2. Adding data
  3. Save all TStringGrid data to json.

Need some example.

Thanks.

4

3 回答 3

25

将以下结构提供给 JSON 对象的代码示例,然后保存到文件:

(*
{
  "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;
于 2013-05-28T11:13:19.607 回答
7

阅读帮助文件:https ://github.com/hgourvest/superobject/blob/master/README.md

然后阅读 TSuperArray 的源代码(“使用源代码,Luke”)

结果如下:

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;

还有来自帮助文件的引用: obj['foo[]'] := value; // 添加一个项目数组
这提出了另一种填充数组的方法(如果根对象本身不是数组)。引用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;

后来这个对象数组作为属性插入到另一个对象中

    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;
于 2013-05-28T10:59:37.290 回答
-1

一个非常好的库是 LkJson:http: //sourceforge.net/projects/lkjson/

解析:

var jsText:字符串;jsObj : TlkJSON 对象;开始

jsObj:=TlkJSON.ParseText(jsText) as TlkJSONobject;

要将其转换回文本:

jsText := TlkJSON.GenerateText(jsObj);
于 2013-05-30T19:32:32.803 回答