2

I'm trying to get values from nsdata class and doesn't work.

here is my JSON data.

{
    "count": 3,
    "item": [{
        "id": "1",
        "latitude": "37.556811",
        "longitude": "126.922015",
        "imgUrl": "http://175.211.62.15/sample_res/1.jpg",
        "found": false
    }, {
        "id": "3",
        "latitude": "37.556203",
        "longitude": "126.922629",
        "imgUrl": "http://175.211.62.15/sample_res/3.jpg",
        "found": false
    }, {
        "id": "2",
        "latitude": "37.556985",
        "longitude": "126.92286",
        "imgUrl": "http://175.211.62.15/sample_res/2.jpg",
        "found": false
    }]
}

and here is my code

-(NSDictionary *)getDataFromItemList
{

    NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)]; 
    NSDictionary *iTem = [[NSDictionary alloc]init];
    iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"id = %@",[iTem objectForKey:@"id"]);

    //for Test
    output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
    NSLog(@"%@",output);
    return iTem;

}

how can I access every value in the JSON? Please help me.

5
  • What is not working? Where does buffer come from? Commented Jun 21, 2012 at 9:11
  • If you are parsing JSON, why not use SBJsonParser. It will help you get everything you need in the form of plain data structures. Or is there any point that you are missing in the question. Commented Jun 21, 2012 at 9:11
  • buffer is from inputStream. I want to get data from the buffer is from server and type is JSON like above. I don't want to use any other library. I'm using ARC, and sometime ARC doesn't allow converting a library to ARC code. Commented Jun 21, 2012 at 9:39
  • How about looking at the error information coming from NSJSONSerialization and posting that? Commented Jun 21, 2012 at 23:53
  • I got this err msg. Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0xde6c4d0 {NSDebugDescription=Garbage at end.} Commented Jun 22, 2012 at 2:03

5 Answers 5

4

look like this ..

NSString *jsonString = @"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
    //this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
    if (jsonError == nil) {
        //every need check value is null or not , json null like ( "count": null )
        if (dic == (NSDictionary *)[NSNull null]) {
            return nil;
        }

        //every property you must know , what type is

        if ([dic objectForKey:@"count"] != [NSNull null]) {
            [self setCount:[[dic objectForKey:@"count"] integerValue]];
        }
        if ([dic objectForKey:@"item"] != [NSNull null]) {
            NSArray *itemArray = [dic objectForKey:@"item"]; // check null if need
            for (NSDictionary *itemDic in itemArray){
                NSString *_id = [dic objectForKey:@"id"]; // check null if need
                NSNumber *found = (NSNumber *)[dic objectForKey:@"found"];
                //.....
                //.... just Dictionary get key value
            }

        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I did it by using the framework : http://stig.github.com/json-framework/

It is very powerfull and can do incredible stuff !

Here how I use it to extract an item name from an HTTP request : (where result is the JSO string)

NSString *result = request.responseString;

jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */

NSDictionary *jsonDict = [jsonArray objectAtIndex:0];

/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:@"wine_name"];

Hope this will be helpfull

3 Comments

Where did you get @"wine_name" from?
This is a key in my JSON string {"wine_name":"some wine name"}
But what does that have to do with the question? He already extracted the NSDictionary correctly from the JSON... Never mind.
1

Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.

NSArray *items = [iTem objectForKey:@"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
   [NSPredicate predicateWithFormat:@"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];

1 Comment

How about the other log statements? Trace back with logs and find out what is nil. Maybe your input string? This is how you will find the error.
1

Try JSONKit for this. Is is extremely simple to use.

Comments

0

Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial There is no need to import any JSON framework. (+1 if this answer is relevant)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.