How to parse JSON in an iOS application

Im getting a response from twitter as a string,

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

here is an example string

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

so I really need messages after "text": "=

@KristinaKlp saluditos y besos d colores

So, how can I take a string and parse it so that I receive all the messages in the array with hope?

Thanks a lot!

+6
source share
6 answers

I did not do JSON while analyzing myself in an iOS application, but you should be able to use a library like json-framework . This library will allow you to easily parse JSON and generate json from dictionaries / arrays (which actually consists of all JSON).

SBJson docs:

JSON maps to Objective-C types as follows:

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

Since Objective-C does not have a dedicated class for Boolean values, they turn into NSNumber instances. However, since this is initialized using the -initWithBool method: they return back to JSON properly. In other words, they will not suddenly suddenly become 0 or 1; they will again be presented as "truth" and "false."

As optimization integers, up to 19 digits in length (maximum length for signed long long integers) are converted to NSNumber instances, while complex ones are converted to NSDecimalNumber instances. This way we can avoid any loss of precision, since JSON allows ridiculously large numbers.

@page objc2json Objective-C for JSON

Objective-C types map to JSON types as follows:

  • NSNull β†’ null
  • NSString -> string
  • NSArray β†’ Array
  • NSDictionary -> Object
  • NSNumber -initWithBool: YES β†’ true
  • NSNumber -initWithBool: NO β†’ false
  • NSNumber β†’ number

@note In JSON, the keys of an object must be strings. NSDictionary keys are optional, but trying to convert NSDictionary from non-linear keys to JSON throw an exception.

NSNumber instances created using the -numberWithBool: method translate to logical "true" and "false" JSON values ​​and vice versa. Any other instances of NSNumber are converted to a JSON number as you expected.

Textbooks

Are there any textbooks? Yes! These are all the tutorials provided by third parties:

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

There are other libraries that you can check, as well as TouchJSON, JSONKit, another JSON library.

+10
source

NSJSONSerialization does the job of converting your JSON data into usable data structures like NSDictionary or NSArray very well. I recommend it even more because it is part of Cocoa's open interface and is supported by Apple.

However, if you want to map the contents of your JSON to your Objective-C objects, you will need to map each attribute from NSDictionary / NSArray to your object property. It can be a little painful if your objects have many attributes.

To automate the process, I recommend that you use Motis (a personal project) for NSObject to execute it, so it is very light 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 JSON object attribute mapping for your Objective-C object property names in 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 do 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. } 

Setting properties from the dictionary is done using KeyValueCoding (KVC), and you can check each attribute before setting it using KVC check.

+4
source

For a good comparison of the speed of various libraries for JSON parsing on iOS, consider The Ultimate Showdown .

+1
source

I had to do this recently. After looking at the various options, I threw JSONKit into my application (I found it in the JSON discussion on StackOverflow). What for? A) VERY VERY simple. I mean, all he has is basic parsing / emitting functions, what else do you need? B) VERY VERY FAST. No overhead - just get the job done.

I should note that I have never done JSON before - I only heard this term and did not even know how to write it. I left nothing, in a working application, in an hour. You simply add one class to your application (.h, .m), create an instance of it, and call the parser on the dictionary object. Voila. If it contains an array, you just get objectForKey, throw it like an NSArray. It is very difficult to do easier and very fast.

+1
source
 -(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]; } 
+1
source

Source: https://habr.com/ru/post/897899/


All Articles