iOS fetching json object from json string - ios

#"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);

Related

Getting Web service response in string Format

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.

How to convert data string to json object and string in iOS?

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];

Json values into NSArray Parsing in IOS

How to store this data in NSArray?
I'm getting JSON response in this format like this:
{
1 = USA;
4 = India;
}
I need to convert this into NSArray
If your JSON is a string, get an NSData object first:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Then turn it into an NSDictionary using the NSJSONSerialization class:
NSError* error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
Since you said you want an NSArray, do the following:
NSArray *jsonArray = [jsonDict allValues];
Note that the order of the entries in the array is undefined, according to Apple's documentation. So if you need a particular order, you'll have to figure out a better approach.
This is JSON dictionary, First you convert this to NSDictionary from JSON.
NSDictionary *dictionary = //parse json using NSJSONSerilization
NSArray *array = [dictionary allValues];
allValues will return an array with all objects.
Try this:
NSString *jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dictionary =[jsonString JSONValue];
NSArray *array = [dictionary allValues];
NSLog(#"Array values = %#",array);

#"{\"details\": \"A friend request is already pending.\"}" how to retrieve the value from this json string

#"{\"details\": \"A friend request is already pending.\"}".. This is a json string coming from the server. i want to retrieve the object in a one string i.e is A friend request is already pending string is to be in one string. please tell me how to retrieve this.
i tried like this
NSString *str = #"{\"details\": \"A friend request is already pending.\"}";
NSLog(#"%#",str);
NSString *resultStr1 = [str stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSString *resultStr2 = [resultStr1 stringByReplacingOccurrencesOfString:#"}" withString:#""];
//NSLog(#"%#",resultStr2);
//NSString *encodestr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(#"%#",encodestr);
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
data = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];
NSLog(#"%#",data);
NSError *error =Nil;
NSArray *JSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",JSON);
NSLog(#"%#",[JSON valueForKey:#"details"]);
Try this. COnvert your string into a dictionary and access it by keys. This will be helpful when you come across large group of data.
NSString *str = #"{\"details\": \"A friend request is already pending.\"}";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", [dic objectForKey:#"details"]);
Try this may be it will help you
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: str dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &e];
NSLog(#"%#",[JSON valueForKey:#"details"]);

how to delete the Superfluous Escape-character in a NSString object

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;
}

Resources