简体   繁体   中英

How to successfully convert JSON data to Objective-C objects?

So the jist of what I'm doing is simple, getting some data from a server in JSON format. I'm using the default classes in Objective-C (specifically NSJSONSerialization) to convert the responseData gotten into JSON format.

So basically-

   NSString* testURL=@"http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=Kendrick+Lamar&track=A.D.H.D&api_key=e3f53f2f2896b44ff158a586b8ee15c7&format=json";

   NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:testURL]];

   NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData //1
                      options:kNilOptions
                      error:&error];

   NSArray* songList = [json objectForKey:@"similartracks"];

Problem is, later when I try to access an indivdual object in the array of JSOn data, like so,

   NSDictionary* song1 = [songList objectAtIndex:0];

It's giving me this error,

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x96e2b60'

Any ideas as to why this is happening?

I appreciate the help, coffeejay

似乎[json objectForKey:@"similartracks"]返回一个NSDictionary,尝试这样的事情:
NSArray* songList = [[json objectForKey:@"similartracks"] objectForKey:@"track"]

When dealing with such things, you should always validate your response before trying to do something with it, you should never trust any input. In your case, you're trying to send objectAtIndex: message to an NSDictionary instance, which raises unrecognised selector exception.

A simple way to avoid such crashes is to check the class of the returned object, for instance:

id song1 = json[@"similartracks"]
if([song1 isKindOfClass:[NSArray class]])
{
    //Now we're sure it's an array
}

您声明返回的数据是data ,但是您正在向NSJSONSerialization方法传递一个名为responseData的变量。

Your json probably doesn't return an array at yhat point but a dictionary. Show the json content so we can help further.

(NsJSonSerialization returns id and can be either an array or dictionary. The contents again will be arrays or dictionaries)

Your error message says that songList is a dictionary and not an array. Check the data structure.

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