如何用Delphi解析Json

时间:2013-08-03 10:57:25

标签: json delphi delphi-2007

需要解析以下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(也许并非完全错误,但并非意图)

1 个答案:

答案 0 :(得分:6)

感谢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;