IOS Objective-C JSON Parse轉成Dictionary
- Parse json object into a dic
- - ( void ) fetchedData: (NSData *) responseData { / / Parse out the JSON dataNSError * Error;
- NSDictionary * json = [NSJSONSerialization
- JSONObjectWithData: responseData / / 1
- options: kNilOptions
- error: & error];
- NSArray * latestLoans = [JSON objectForKey: @ "loans" ]; / / 2
- NSLog (@ "loans:% @" , latestLoans); / / 3
- }
- Generate json string to object
- / / Build an info object and convert to json
- NSDictionary * info = [NSDictionary dictionaryWithObjectsAndKeys: [Loan objectForKey: @ "name" ],
- @ "who" ,
- [(NSDictionary *) [Loan objectForKey: @ "location" ]
- objectForKey: @ "Country" ],
- @ "where" ,
- [NSNumber numberWithFloat: outstandingAmount],
- @ "what" ,
- nil];
- / / Convert object to data
- NSData * jsonData = [NSJSONSerialization dataWithJSONObject: info
- options: NSJSONWritingPrettyPrinted error: & error];
- / / Print out the data contents
- jsonSummary.text = [[NSString alloc] initWithData: jsonData
- encoding: NSUTF8StringEncoding];
- Add json method to dic
- @ InterfaceNSDictionary (JSONCategories)
- + (NSDictionary *) dictionaryWithContentsOfJSONURLString: (NSString *) urlAddress;
- - (NSData *) toJSON;
- @ End
- @ ImplementationNSDictionary (JSONCategories)
- + (NSDictionary *) dictionaryWithContentsOfJSONURLString: (NSString *) urlAddress {
- NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress]];
- __autoreleasing NSError * error = nil;
- id result = [NSJSONSerialization JSONObjectWithData: data
- options: kNilOptions error: & error];
- if (Error! = nil) returnnil;
- return result;
- }
- - (NSData *) toJSON {
- NSError * error = nil;
- id result = [NSJSONSerialization dataWithJSONObject: self
- options: kNilOptions error: & error];
- if (Error! = nil) returnnil;
- return result;
- } @ End
- Use Liezi
- NSDictionary * MyInfo = [NSDictionary dictionaryWithContentsOfJSONURLString: @ "http://www.yahoo.com/news.json" ];
- NSDictionary * information = [NSDictionary dictionaryWithObjectsAndKeys: @ "Orange" , @ "Apple" , @ "Banana" , @ "fig" , nil];
- NSData * json = [information toJSON];
- Determine whether the json of
- BOOL isTurnableToJSON = [NSJSONSerialization isValidJSONObject: object]
留言