Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it. Android provides four different classes to manipulate JSON data.
With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization
, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.
So, for example:
NSData *returnedData = ...JSON data, probably from a web request...
// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?
if(NSClassFromString(@"NSJSONSerialization"))
{
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:returnedData
options:0
error:&error];
if(error) { /* JSON was malformed, act appropriately here */ }
// the originating poster wants to deal with dictionaries;
// assuming you do too then something like this is the first
// validation step:
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *results = object;
/* proceed with results as you like; the assignment to
an explicit NSDictionary * is artificial step to get
compile-time checking from here on down (and better autocompletion
when editing). You could have just made object an NSDictionary *
in the first place but stylistically you might prefer to keep
the question of type open until it's confirmed */
}
else
{
/* there's no guarantee that the outermost object in a JSON
packet will be a dictionary; if we get here then it wasn't,
so 'object' shouldn't be treated as an NSDictionary; probably
you need to report a suitable error condition */
}
}
else
{
// the user is using iOS 4; we'll need to use a third-party solution.
// If you don't intend to support iOS 4 then get rid of this entire
// conditional and just jump straight to
// NSError *error = nil;
// [NSJSONSerialization JSONObjectWithData:...
}
Don't reinvent the wheel. Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary
:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"];
//将文件内容读取到字符串中,注意编码NSUTF8StringEncoding 防止乱码,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//将字符串写到缓冲区。
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
for (int i=0; i<[allKeys count]; i++) {
NSDictionary *arrayResult = [allKeys objectAtIndex:i];
NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]);
}
file:
[
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "MLMember",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
},
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "0.00",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
}
]
JSON parsing using NSJSONSerialization
NSString* path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
//Here you can take JSON string from your URL ,I am using json file
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSLog(@"jsonDataArray: %@",jsonDataArray);
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
// NSString *errorCode=[NSMutableString stringWithFormat:@"%@",[jsonObject objectForKey:@"response"]];
if(![[jsonObject objectForKey:@"#data"] isEqual:@""]){
NSMutableArray *array=[jsonObject objectForKey:@"#data"];
// NSLog(@"array: %@",array);
NSLog(@"array: %d",array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:@"%d",k];
NSDictionary *dicr = jsonObject[@"#data"][strfd];
k=k+1;
// NSLog(@"dicr: %@",dicr);
NSLog(@"Firstname - Lastname : %@ - %@",
[NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_first_name"]],
[NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_last_name"]]);
}
}
}
You can see the Console output as below :
Firstname - Lastname : Chandra Bhusan - Pandey
Firstname - Lastname : Kalaiyarasan - Balu
Firstname - Lastname : (null) - (null)
Firstname - Lastname : Girija - S
Firstname - Lastname : Girija - S
Firstname - Lastname : (null) - (null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With