【问题标题】:How do I parse Json with Delphi [closed]如何使用 Delphi 解析 Json [关闭]
【发布时间】:2013-08-03 10:57:24
【问题描述】:

需要解析以下 JSON 但不知道如何使用 D2007 和 uJSON 有人可以向我展示如何访问这些值的示例吗?

{
    "id": "40",
    "created_at": "2013-08-02 20:50:28",
    "delivery_at": "2013-08-02 20:50:28",
    "cid": "7",
    "firstname": "Joe",
    "lastname": "Average",
    "street": "Joes Place",
    "items": [
        {
            "id": 601,
            "price": 25,
            "name": "Pizza Party 40x60 cm",
            "qty": 1,
            "opt": 8,
            "extras": [
                [
                    "Salmon",
                    0
                ],
                [
                    "Spinach",
                    1.5
                ],

            ]
        }
    ],
    "eMail": "me@examble.com"
}

提前致谢!

编辑:更正了错误的 json(可能不是完全错误,但不是故意的)

【问题讨论】:

  • 您可以查看SuperObject 以及作为uJson 替代方案的示例
  • 您的 json 无效。 Items 嵌套值是一个字符串,而不是一个有效的 json 数组...
  • 这不会使其 JSON 无效,@Arnaud。 happen 的字符串值之一完全有可能包含本身可以被解释为更多 JSON 的内容。不过,是否允许 JSON 字符串包含换行符是另一回事。
  • Op 确实修复了它的 json。如规范所述,应该转义换行符..

标签: json delphi delphi-2007


【解决方案1】:

感谢 Rufo 爵士,我用 SuperObject 进行了尝试,我可以让它工作。 在这里,我的解决方案希望对其他人有所帮助。不知道这是否是最短的方法,但它有效。

但是,如果您可以编写一些较短的代码,请随时编辑此答案。 (如果你能纠正我糟糕的英语;)

var
   order, pos: ISuperObject;
   firstname, lastname, street, created_at, delivery_at, cid, eMail : String;
   id, i : Integer;
begin

       order := SO(<jsontext>);

       id := order.AsObject.I['id'];
       fistname := order.AsObject.S['firstname'];
       lastname := order.AsObject.S['lastname'];
       street := order.AsObject.S['street'];
       cid := order.AsObject.S['cid'];
       eMail := order.AsObject.S['eMail'];
       created_at := order.AsObject.S['created_at'];
       delivery_at := order.AsObject.S['delivery_at'];

       // do some stuff with your values
       // and next are the articles of our pizza order ;)
       for pos in order['items'] do begin

           // get the values like this
           ShowMessage(pos['name'].AsString)
       end;

       // and now the array of extra ingredients for an particular article

       for i := 0 to pos['extras'].AsArray.Length - 1 do begin

            // do some stuff here we Show it again only for demonstration purpose
            ShowMessage(pos['extras[' + IntToStr(i) + '][0]'].AsString)
       end

end;

【讨论】:

  • 您上次编辑的原因是什么?你还在寻找答案吗?对什么问题?如果您有任何问题,请随时发布新问题或更新此问题,但不要指望有人回答
  • 不,抱歉,一切正常
猜你喜欢
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 2020-09-20
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多