I'm a newbie about development of iOS.
And when I deal a json with NSJSONSerialization , I find something really a problem to me.
NSLog(#"response: %#", responseString);
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"dict: %#", dict);
and the output is:
2013-03-18 20:13:56.228 XXXX[3550:5003] response: {"status":"success","data":"{\"title\":\"\",\"sessionName\":\"sid\",\"sessionID\":\"9217e5df3db6b4b4aa3eed800890069f\",\"rand\":5360}","md5":"292ee1e78628fc6360c647e938c4f1ea"}
2013-03-18 20:13:56.229 XXXX[3550:5003] dict: {
data = "{\"title\":\"\",\"sessionName\":\"sid\",\"sessionID\":\"9217e5df3db6b4b4aa3eed800890069f\",\"rand\":5360}";
md5 = 292ee1e78628fc6360c647e938c4f1ea;
status = success;
with the "\" the data section cannot be a NSDictionary object
So what should I do to make it right?
Sorry for my poor English.
For whatever reason, the value of "data" is not a JSON dictionary, but a string containing JSON data. You can fix this by applying JSONObjectWithData to this string again and replacing the value in the dictionary:
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSData *nestedJsonData = [[dict objectForKey:#"data"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *nestedDict = [NSJSONSerialization JSONObjectWithData:nestedJsonData options:NSJSONReadingMutableContainers error:nil];
[dict setObject:nestedDict forKey:#"data"];
NSLog(#"dict: %#", dict);
Output:
dict: {
data = {
rand = 5360;
sessionID = 9217e5df3db6b4b4aa3eed800890069f;
sessionName = sid;
title = "";
};
md5 = 292ee1e78628fc6360c647e938c4f1ea;
status = success;
}
Related
#"SaveRegistrationIDResult" : #"{\"Table\":[{\"Return_Code\":1,\"Return_Message\":\"ALREADY REGISTERED\"}]}"
I'm finding it impossible to fetch data from this json string.
I'm getting the table Table Object as a NSDictionary using this code.
NSMutableDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSData *processedJsondata = [jsonData objectForKey:#"SaveRegistrationIDResult"];
but I getting errors for everything i try ahead.
I'd like to fetch data from within the Table array ('Return_Code') and print it in a Log.
You are getting json string so you can parse it like,
id jsonString = #"{\"Table\":[{\"Return_Code\":1,\"Return_Message\":\"ALREADY REGISTERED\"}]}"; // or [yourDictionary objectForKey : #"SaveRegistrationIDResult"];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now you can get value of any key from above object like,
NSArray *arr = [jsonObject objectForKey : #"Table"];
NSLog(#"your result : %#", arr);
Lion's comment worked.
This is how I fetched the value. Any optimizations welcome.
NSMutableDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *processedJsondata = [jsonData objectForKey:#"SaveRegistrationIDResult"];
NSData *tableData = [processedJsondata dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *tableJsonObject = [NSJSONSerialization JSONObjectWithData:tableData options:0 error:nil];
NSArray *tableArray = [tableJsonObject objectForKey:#"Table"];
NSDictionary *tableObject = [tableArray objectAtIndex:0];
NSString *reposnseCode = [tableObject objectForKey:#"Return_Message"];
NSLog(#"%#",reposnseCode);
I am using Afnetworking Framework in my project but I am getting the response in string format. I want to get the value of "Data" in the response below -
"{\"Result\":\"Success\",\"Data\":\"intro-1898-1449000428650.mp4\"}"
I have used the code below:
[Helper PostWebServiceRequest:kIntrovideo InputParameters:parameters competion:^(BOOL result, NSDictionary *response) {
if (result){
NSLog(#"response : %#",response);
NSString *data= [NSString stringWithFormat:#"%#",response ];
NSError *jsonError;
NSData *objectData = [data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
since your response object seems to be an array and not (as stated) a dictionary, try the following:
NSString *jsonString = ((NSArray *)response).firstObject;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSString *data = jsonObject[#"Data"];
Not sure, but it seems that server can't pass object in Json, it's should pass link to place from where you can download this Data.
I have a String format of JSON
{
abstract = "Today P.M of India Mr. Narender Modi visited for the eve of Agarasen \njayanti
\n";
created = 1444733102;
imgUrl = "";
nid = 12;
title = "Latest news";
}
I want to converted To NSDictionary
NSError *jsonError;
NSData *objectData = [[[tableDataArray objectAtIndex:indexPath.row]objectForKey:#"NewsValue"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"%#",json);
They Give response is Null Please Help.
This is already in Json data of dictionary formate.
so you need not convert. Just retrieve data.
NSString * abstract = [Dic valueForKey:#"abstract"];
Please used below code
NSData *objectData = [[[tableDataArray objectAtIndex:indexPath.row]objectForKey:#"NewsValue"]
NSString *strResponce = [[NSString alloc] objectData encoding:NSUTF8StringEncoding];
NSMutableDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:[strResponce dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];
if([dictResponse isKindOfClass:[NSMutableDictionary class]]) {
NSString * abstractStr = [dictResponse valueForKey:#"abstract"];
}
How to convert string to JSON object or JSON array in iOS?
my JSON string Like That.
{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}
I want to get ID or Name from this string please help me if anyone now this.
Thank You.
I try below code but print null
NSString *JsonString=#"{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}";
NSData *objectData = [JsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&error];
NSArray* array = [json objectForKey:#"Data"];
NSLog(#"Print Array %#",array);
Use this
NSString *str=#"{\"Data\": [{\"ID\":\"1\",\"Name\":\"Raj\"},{\"ID\":\"2\",\"Name\":\"Rajneesh\"}]}";
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
NSMutableArray *dataArr=[dict valueForKey:#"Data"];
for (NSDictionary *userData in dataArr) {
NSLog(#"Id:%# Name:%#",[userData valueForKey:#"ID"],[userData valueForKey:#"Name"]);
}
Always Remember that when there are { } curly brackets, it means it is Dictionary and when [ ] this, means Array
NSURL *url=[NSURL URLWithString:#"Your JSON URL"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *array = json[#"Data"];
for(NSMutableDictionary *dic in array)
{
NSLog(#"%#",dic[#"ID"]); // give 1 & 2
NSLog(#"%#",dic[#"Name"]); // Raj and Rajneesh
}
This is not the correct JSON string which can be parsed by Objective c, get string from encoder and you will get a valid string, other then that for JSON to Dictionary conversion is simple in iOS as its natively supported.
NSData *data = [strJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
Problem: I can't parse data from a JSON file to a NSArray appropriately. UTF encoding is not working as expected.
My JSON looks something like:
[
{"Name":"Marcos","Address":"1234 Brasil Av. São Paulo - SP","Latitude":"-23.000","Longitude":"-46.70"},{"Name":"Mario","Address":"1000 Washignton Luiz Av. Itú SP","Latitude":"-20.0000","Longitude":"-46.000"}
]
My Objective-C code is:
NSError *error = nil;
NSURL *jsonUrl = [[NSURL alloc]initWithString:
#"http://marcosdegni.com.br/teste/webservice_teste.php"];
NSString *jsonString = [NSString stringWithContentsOfURL:jsonUrl
encoding:NSUTF8StringEncoding error:&error];
NSLog(#"jsonString: %# , Error:%#:" ,jsonString, error); //(1)
if (!error) {
NSError *error2 = nil;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray * jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error2];
NSLog(#"\n\nArray: %#" \nError:$#, jsonArray, error2); //(2)
//(*1*) This log show the content's as they are expected: note the characters ã and ú on the address fields.
//(*2*) The logs from the array and the dictionary show this charters as it's UNIX codes:\U00e and \U00fa respectively.
You can give this a try. The id json you get will be a NSArray, you can use it from there.
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray * array = json;
for (NSDictionary *dict in array) {
NSString *string = [dict objectForKey:#"Address"];
NSLog(#"%#",string);
}
From here, and I get the right result if I obtain the value of the key and log it, instead of logging the NSArray directly.