How to parse received response [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am very new to iOS application development and I am getting the below response from the server:
"[{\"EmployeeID\":\"000001\",\"EmplyeeName\":\"ABCD EFGHI\"},
{\"EmployeeID\":\"000002\",\"EmplyeeName\":\"ADGHT ASASASAS\"}]"
Please anybody help me out on how to use employee ID and employee name in my application.

Your JSON data looks like "nested JSON", which means that you have to deserialize it twice.
The first deserialization extracts a string from your JSON data:
NSData *response = ...; // your data
NSError *error;
NSString *innerJson = [NSJSONSerialization JSONObjectWithData:response
options:NSJSONReadingAllowFragments error:&error];
Now innerJson is the string
[{"EmployeeID":"000001","EmplyeeName":"ABCD EFGHI"},{"EmployeeID":"000002","EmplyeeName":"ADGHT ASASASAS"}]
which is again JSON data. The second deserialization extracts the array:
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[innerJson dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
And now you can access it like
for (NSDictionary *entry in entries) {
NSString* employeeID = [entry objectForKey:#"EmployeeID"];
NSLog(#"%#", employeeID);
}

NSData *response = ...;
NSArray *entries = [NSJSONSerialization JSONObjectWithData:response
options:0
error:nil];
for(NSDictionary* entry in entries) {
NSString* employeeID = [entry objectForKey:#"EmployeeID"];
}

Look JSON Parser your response is JSON so you need to get that data from json.
NSURL * url=[NSURL URLWithString:#"<YourURL>"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
NSMutableArray * EmployeeID=[[NSMutableArray alloc]init];
NSMutableArray * EmployeeName=[[NSMutableArray alloc]init];
NSArray * responseArr = json[#"geonames"];
for(NSDictionary * dict in responseArr)
{
[EmployeeID addObject:[dict valueForKey:#"EmployeeID"]];
[EmployeeName addObject:[dict valueForKey:#"EmplyeeName"]];
}
now you get the EmployeeID,EmployeeName array now you can used anywhere where you want.

Take a look at:
NSJSONSerialization

Use this:
NSData* yourData = [[NSData alloc] initWithContentsOfURL: yourURL];
NSarray* yourJSON = [NSJSONSerialization JSONObjectWithData:yourData options:kNilOptions error:nil];
Hope this help you :)

Try to use this:
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];

Related

How to parse {status:0,val:450} from a HTML response

i want to take 450
from the following:
NSString {status:0,val:450}
using objective c:
{status:0,val:450}
Please suggest me answer
I cannot completely understand your question . I think you have you have an JSON data like:
{
status:0;
val:450;
}
If you want this data in your app. You want to do
NSURL *blogURL = [NSURL URLWithString:#"https://your url here"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *data = [dataDictionary objectForKey:#"status"];
NSDictionary *item = [data objectForKey:#"val"];
Your JSON Data get in Dictionary format. You can access the Data using the Key. In here your keys are status and val.
I hope this links are help for you.
fetch parse json ios programming tutorial
and this Link:
json parsing in ios

Null JSON response

NSString *connection = #"http:"(link);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:connection];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(#"\nJSON: %# \n Error: %#", json, error);
if(!error) {
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonData);
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"JSON: %#", jsonDict);
}
});
The above code returns :
JSON: "{\"value\":[{\"Id\":\" }}
but
NSData is 69746963 735c222c 5c224973 41767469 76655c22 3a5c2231 5c222c
and jsonDict returns (null).
I am confused what may be going on.
Can somebody please help me figure it out.
I am trying to get the JSON data but it returns null.
Thanks
You say the server gave you this:
JSON: "{\"value\":[{\"Id\":\" }}
If I remove the backslashes that were added by the NSLog command, the actual JSON that you received was
{"value":[{"Id":" }}
That isn't valid JSON. That's all there is to it; the server sent you rubbish data, and there is no way to get any information from it. Contact the people creating the server software and ask them to fix the problem.
And you really, really need to distinguish between what an object really contains, and what NSLog prints. NSLog prints the contents of an NSData object by displaying each byte as two hexadecimal digits.
Try one of these (array or dictionary) without converting it into JSON, depending on what u want :
NSString *connection = #"http://(link)";
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSDictionary *jsonDict = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:connection]];
NSArray *jsonArray = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:connection]];
NSLog(#"DICT: %# ARRAY: %#", jsonDict, jsonArray);
});
I haven't tried it, please paste results?
By the look of your NSString response, it starts with { and ends with } which means it is a NSDictionary.
Change :
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
to :
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&error];

How to parse JSON Parsing in iOS [duplicate]

This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
I have some values in an array ,using dictionary I need to show these values through some key value
{
"table_id": "180PTTBL",
"table_name": "180 Points",
"stake": 100,
"game_type": "180PT"
}
Please help me out this problem
You can use NSJSONSerialization
NSError *e = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!dict) {
NSLog(#"Error parsing JSON: %#", e);
} else {
.. do your stuff
}
NSString *jsonString = #"YOUR_JSON_STRING";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",[json objectForKey:#"table_id"]);

NSJSONSerialization doesn't parse this JSON

I'm trying to parse this JSON that looks to me like well written, but NSJSONSerialization doesn't think the same AFAIK since it's returning an NSArray.
This is my code:
NSData* gamesData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://s42sport.com/polarice/json/games.json"]
];
NSDictionary* json = nil;
if (gamesData) {
json = [NSJSONSerialization
JSONObjectWithData:gamesData
options:kNilOptions
error:nil];
NSLog(#"%d",json.count);
}
The questions are,
What's wrong with the JSON? Why NSSerialization doesn't return me the NSDictionary?
Edit: Yes, I just learned about the [...] vs {...}. Thank You.
Parse your json by this way.
NSURL * url=[NSURL URLWithString:#"http://s42sport.com/polarice/json/games.json"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"%#",json);
NSArray * array1=[json valueForKey:#"c"];
NSLog(#"%#",array1);
Try this code. this will surely work for you.
NSDictionnary should be used for Object whereas NSArray is use for JSON array
NSArray* json = nil;
if (gamesData) {
json = [NSJSONSerialization
JSONObjectWithData:gamesData
options:kNilOptions
error:nil];
NSLog(#"%d",json.count);
}
The JSON file you listed is an array (it starts and ends with a square bracket) so Objective-C reflects that with an NSArray root object.

How to build JSON string of particular format? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to format a JSON string of below format using NSJSONSerialization:
{
"data":{"userName":"rrullo","password":"rrullo!"},
"meta":{"appId":"S3B9CU4R2B9JTXV9254Y","appVersion":"2.1.0","serverVersion":"1.1.0","platform":"iOS","deviceToken":"1234","tm_session_id":"BB0000001234"}
}
But I have no clue how to achieve this format though. Can someone help me please ......
First fill two NSDictionaries with your 'meta' and 'data' info. Then add those into a main NSDictionary and then serialize using NSJsonSerialization
NSDictionary * metaDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"appId", #"S3B9CU4R2B9JTXV9254Y", #"appVersion", #"2.1.0", #"serverVersion", #"1.1.0", #"platform", #"iOS",..., nil];
NSDictionary * dataDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"userName", #"rrullo", #"password", #"rrullo!", nil];
NSDictionary * mainDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"data", dataDict, #"meta", metaDict, nil];
Now you can use NSJsonSerialization to convert that mainDict to a NSString
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mainDict
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Hope this helps
NSDictionary dictData = #{ #"UserName":#"rrullo", #"password":#"rrullo!"};
NSDictionary dictMeta = #{ #"appId":#"S3B9CU4R2B9JTXV9254Y", etc};
NSDictionary dictJSON = #{ #"data":dictData, #"meta":dictMeta };
NSError *error = nil;
NSData *dataJSON = [NSJSONSerialization dataWithJSONObject:dictJSON
options:NSJSONWritingPrettyPrinted
error:&error];
if (!error) {
NSString *jsonString = [[NSString alloc] initWithData:dataJSON encoding:NSUTF8StringEncoding];
} else {
NSLog(#"Error: %#", error);
}

Resources