简体   繁体   中英

Downloading and parsing JSON kit on iOS

I am trying to parse this from a webserver to a tableview in iOS

{
  "transactions": [
    {
    "ID": "350",
    "description": "Macbook Pro 17 inch",
    "price": "2811.83"
    },
    {
    "ID": "351",
    "description": "Macbook - white",
    "price": "1720.10"
    },
    {
    "ID": "352",
    "description": "iPad 2",
    "price": "650.00"
    },
    {
    "ID": "353",
    "description": "Macbook Pro 17 inch",
    "price": "3233.98"
    },
    {
    "ID": "354",
    "description": "Macbook Pro 15 inch",
    "price": "2100.55"
    },
    {
    "ID": "355",
    "description": "Macbook Air",
    "price": "899.99"
    },
    {
    "ID": "356",
    "description": "Mac Pro",
    "price": "3400.77"
    }
  ]
}

The only things I want from this are the descriptions and the prices. I need to add up the price of each item and get a total. Each transaction name needs to be stored in an NSArray and then displayed in a UITableView .

Any help? The JSONkit doesnt give me the SBJSON parser

I really liked JSONKit because of its simplicity and speed. You have to realize, what it returns is the top level construct as an object - so you have to think about it. It will be a NSDictionary (so you can typecast it), and it will have one key "transactions".

This key will return an NSArray of NSDictionary objects, each of which will have the keys ID, description, and price.

So something like this (where itemListData is the JSON data fetched from the URL for example):

JSONDecoder *decoder = [JSONDecoder decoderWithParseOptions:JKParseOptionStrict];
NSData *immutableItemList = [itemListData copy];
NSArray *returnedData = (NSArray *) [[decoder objectWithData:immutableItemList] objectForKey:@"transactions"];

So, we took the raw JSON data, instantiated a decoder, then decoded it into a dictionary - and retrieved the 1 object in the dictionary (as an array in this case, because that's what it is). Not too bad for a newbie, eh?

(I should add - the reason I make an immutable copy of the NSData, is that this code snippet is in an asynchronous download, triggered in the connectionDidFinishLoading method.)

Hey man so what I have done in the past is go to facebook and download their developer sdk. In that sdk is a great JSON parsing tool. You can find it here http://developers.facebook.com/docs/reference/iossdk/ Then you simply add that to your project and in you header do an

 #import "JSON.h"

and then when you get that string you say

NSDictionary *data = [my_data_string JSONValue];
NSArray *transactions = [data objectForKey:@"Transactions"];

and that should work:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM