How to parse JSON in iOS App

2019-01-06 20:01发布

Im getting a response from twitter in the form of a string,

What I need is to send the parts where is a comment to an array,

here an example of the string

[{"geo":null,"coordinates":null,"retweeted":false,... 
"text":"@KristinaKlp saluditos y besos d colores!"},{"geo":null,"coordinates...

so what I really need are the posts after "text":" =

@KristinaKlp saluditos y besos d colores!

So, how can I take the string and parse it so I get all the messages in an array hopefully?

Thanks a lot!

6条回答
姐就是有狂的资本
3楼-- · 2019-01-06 20:41

I haven't done JSON parsing myself in an iOS App, but you should be able to use a library like the json-framework. This library will allow you to easily parse JSON and generate json from dictionaries / arrays (that's really all JSON is composed of).

SBJson docs:

JSON is mapped to Objective-C types in the following way:

  • null -> NSNull
  • string -> NSString
  • array -> NSMutableArray
  • object -> NSMutableDictionary
  • true -> NSNumber's -numberWithBool:YES
  • false -> NSNumber's -numberWithBool:NO
  • integer up to 19 digits -> NSNumber's -numberWithLongLong:
  • all other numbers -> NSDecimalNumber

Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber instances. However, since these are initialised with the -initWithBool: method they round-trip back to JSON properly. In other words, they won't silently suddenly become 0 or 1; they'll be represented as 'true' and 'false' again.

As an optimisation integers up to 19 digits in length (the max length for signed long long integers) turn into NSNumber instances, while complex ones turn into NSDecimalNumber instances. We can thus avoid any loss of precision as JSON allows ridiculously large numbers.

@page objc2json Objective-C to JSON

Objective-C types are mapped to JSON types in the following way:

  • NSNull -> null
  • NSString -> string
  • NSArray -> array
  • NSDictionary -> object
  • NSNumber's -initWithBool:YES -> true
  • NSNumber's -initWithBool:NO -> false
  • NSNumber -> number

@note In JSON the keys of an object must be strings. NSDictionary keys need not be, but attempting to convert an NSDictionary with non-string keys into JSON will throw an exception.

NSNumber instances created with the -numberWithBool: method are converted into the JSON boolean "true" and "false" values, and vice versa. Any other NSNumber instances are converted to a JSON number the way you would expect.

Tutorials

Are there any tutorials? Yes! These are all tutorials provided by third-party people:

JSON Framework for iPhone - a Flickr tutorial in three parts by John Muchow. JSON Over HTTP On The iPhone - by Dan Grigsby. AS3 to Cocoa touch: JSON by Andy Jacobs.

There are other libraries you can check out as well like TouchJSON, JSONKit, Yet Another JSON Library

查看更多
爷的心禁止访问
4楼-- · 2019-01-06 20:45

I recently had to do this. After looking at the various options out there, I threw JSONKit into my app (I found it on a JSON discussion on StackOverflow). Why? A) It is VERY VERY simple. I mean, all it has is the basic parsing/emitting functions, what more do you need? B) It is VERY VERY fast. No overhead - just get the job done.

I should note, I had never done JSON before - only heard of the term and didn't even know how to spell it. I went from nothing, to a working app, in about 1 hour. You just add one class to your app (the .h, .m), instantiate it, and call the parser to a dictionary object. Voila. If it contains an array, you just get the objectForKey, cast it as an NSArray. It's really hard to get simpler than that, and very fast.

查看更多
forever°为你锁心
5楼-- · 2019-01-06 20:49
-(IBAction)btn_parse_webserivce_click:(id)sender
{
// Take Webservice URL in string.
NSString *Webservice_url = self.txt_webservice_url.text;
NSLog(@"URL %@",Webservice_url);
// Create NSURL from string.
NSURL *Final_Url = [NSURL URLWithString:Webservice_url];
// Get NSData from Final_Url
NSData* data = [NSData dataWithContentsOfURL:
Final_Url];
//parse out the json data
NSError* error;
// Use NSJSONSerialization class method. which converts NSData to Foundation object.

NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
// Create Array
NSArray* Response_array = [json objectForKey:@"loans"];
NSLog(@"Array: %@", Response_array);
// Set Response_array  to textview.
self.txt_webservice_response.text = [NSString stringWithFormat:@"%@"
,Response_array];
}
查看更多
forever°为你锁心
6楼-- · 2019-01-06 20:55

NSJSONSerialization does the job of converting your JSON data into usable data structures as NSDictionary or NSArray very well. I recommend it, even more because it is part of the Cocoa public interface and it is maintained by Apple.

However, if you want to map the content of your JSON to your Objective-C objects, you will have to map each attribute from the NSDictionary/NSArray to your object property. This might be a bit painful if your objects have many attributes.

In order to automatise the process, I recommend you to use the Motis category (personal project) on NSObject to accomplish it, thus it is very lightweight and flexible. You can read how to use it in this post. But just to show you, you just need to define a dictionary with the mapping of your JSON object attributes to your Objective-C object properties names in your NSObject subclasses:

- (NSDictionary*)mjz_motisMapping
{
    return @{@"json_attribute_key_1" : @"class_property_name_1",
             @"json_attribute_key_2" : @"class_property_name_2",
              ...
             @"json_attribute_key_N" : @"class_property_name_N",
            };
}

and then perform the parsing by doing:

- (void)parseTest
{
    NSData *data = jsonData; // <-- YOUR JSON data 

    // Converting JSON data into NSArray (your data sample is an array)
    NSError *error = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

    if (error)
        return; // <--- If error abort.

    // Iterating over raw objects and creating model instances
    NSMutableArray *parsedObjects = [NSMutableArray array];

    for (NSDictionary *rawObject in jsonArray)
    {
        // Creating an instance of your class
        MyClass instance = [[MyClass alloc] init];

        // Parsing and setting the values of the JSON object
        [instance mjz_setValuesForKeysWithDictionary:rawObject];

        [parsedObjects addObject:instance];
    }

    // "parseObjects" is an array with your parsed JSON.
    // Do whatever you want with it here.
}

The setting of the properties from the dictionary is done via KeyValueCoding (KVC) and you can validate each attribute before setting it via KVC validation.

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-06 21:00

For a good comparison of the speed of the different libraries for JSON parsing on iOS, take a look at The Ultimate Showdown.

查看更多
登录 后发表回答