Use Objective-C Json, objective-cjson
Objective-c json
NSJSONSerialization can be used to convert Json and Foundation. The following describes how to use Objective-c json.
Json To Fundation
JSONObjectWithData can be used to convert Json to Foundation. The top layer of Json can be{}
Or[]
Therefore, there are two formats: NSDictionary and NSArray. Read and use ObjectForKey to return the corresponding object.
123456789101112131415161718192021222324252627282930313233 |
NSString * items = @ "{" items ": [" item0 "," item1 "," item2 "]}"; NSData * data = [items dataUsingEncoding: NSUTF8StringEncoding]; NSError * error = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: & amp; error]; if ([jsonObject isKindOfClass: [NSDictionary class]) {NSDictionary * dictionary = (NSDictionary *) jsonObject; NSLog (@ "Dersialized JSON Dictionary = % @", dictionary);} else if ([jsonObject isKindOfClass: [NSArray class]) {NSArray * nsArray = (NSArray *) jsonObject; NSLog (@ "Dersialized JSON Array = % @", nsArray );} else {NSLog (@ "An error happened while deserializing the JSON data. ");} NSDictionary * dict = (NSDictionary *) jsonObject; NSArray * arr = [dict objectForKey: @" items "]; NSLog (@" list is % @", arr ); |
Fundation To Json
DataWithJsonObject can be used to convert Fundation to Json. Options: NSJSONWritingPrettyPrinted is the branch output json, and option: kNilOptions is used for no space output.
The following code is used to obtain the product list in IOS. Add the content to Json.
1234567891011121314151617181920212223242526272829303132333435 |
NSArray * myProduct = response. products; NSDictionary * myDict; NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 4]; for (int I = 0; I & lt; myProduct. count; ++ I) {// NSLog (@ "----------------------"); // NSLog (@ "Product title: % @", [myProduct [I] localizedTitle]); // NSLog (@ "Product description: % @", [myProduct [I] localizedDescription]); // NSLog (@ "Product price: % @", [myProduct [I] price]); // NSLog (@ "Product id: % @", [myProduct [I] productIdentifier]); myDict = [NSDictionary dictionaryWithObjectsAndKeys: [myProduct [I] localizedTitle], @ "title", [myProduct [I] localizedDescription], @ "desc", [myProduct [I] price], @ "price ", [myProduct [I] productIdentifier], @ "product", nil]; [dict setValue: myDict forKey: [myProduct [I] productIdentifier];} if ([NSJSONSerialization isValidJSONObject: dict]) {NSError * error; NSData * str = [NSJSONSerialization dataWithJSONObject: dict options: kNilOptions error: & amp; error]; NSLog (@ "Result: % @", [[NSString alloc] initWithData: str encoding: NSUTF8StringEncoding]);} else {NSLog (@ "An error happened while serializing the JSON data. ");} |
This article is from: [Songyang's blog]/[blog.csdn.net/fansongy] forbidden for commercial purposes reprinted. Please indicate the source
Link: http://www.songyang.net/objective-c-json/