how to parse a JSON string in iphone Objective - C?

吃可爱长大的小学妹 提交于 2019-12-04 21:45:26
Baz1nga

This post should help.

There are some good examples here: http://iosdevelopertips.com/cocoa/json-framework-for-iphone-part-2.html

Little bit of JSON:

This is a JSON array:

["firstValue", "secondValue"]

This is a JSON dictionary:

{
"A key" : "A value",
"Another key" : "Another value"
}

Your JSON is telling the parser that the root type is an array. Therefore, jsonValue is returning an array. You are trying to call objectForKey (NSDictionary method) on that array. That's why the exception was thrown.

Please post your JSON so we can see the structure and how you should parse it. Or, try logging the object you store jsonValue to.


UPDATE:

After reading your JSON, this is how you should parse it:

NSString *jsonString; // set this to your json
NSArray *places = [jsonString jsonValue];
// then iterate through the places, saving off the bits you need
for (NSDictionary *place in places) {
    NSString *placeName = [place objectForKey:@"placesname"]; // for example
    NSLog(@"Name of place: %@", placeName); 
}

What you might want to do is create a custom class called place which has a property for lat, long, placename etc. and then save an array of those.

JSON syntax represents both arrays and dictionaries. When parsing an "unknown" piece of JSON code, you don't know whether a given "layer of the onion" is an array or dictionary, so you must check (at each level) to see what kind of object you have. Use [myObject isKindOfClass:[NSArray class]] and [myObject isKindOfClass:[NSDictionary class]].

It's also not unwise to do this checking even with "known" JSON sources, since web sites can break or change, and it's better to present a nice error message (and blame the web site) rather than have your app crash.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!