Search code examples
jsondelphidelphi-2007

How do I parse Json with Delphi


need to parse the following JSON but can't figure out how to do it with D2007 and uJSON can someone show me a examble how I can access this values?

{
    "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"
}

Thanks in advance!

edit: corrected wrong json (maybe not totally wrong, but not intended)


Solution

  • Thanks to Sir Rufo i tried it with SuperObject and I could get it to work. Here my solution hopefully it will help others. don't know if it the shortest way but it works.

    But if you can write some shorter code feel free to edit this answer. (also if you can correct my poor English ;)

    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;