get object from json string in iOS - Xcode - ios

i have "JSON" String like this.
**
{"success":true,"domains":[{"URL":"","name":"Test
Alpha","id":"100"}]}
**
i want to check is success is true and, if it is true, get the URL.
how can i do this in iPhone application - xcode?

NSData* data = [myStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(YES == dictionary[#"success"])
{
NSString *urlString = dictionary[#"domains"][0][#"URL"];
}

May be hep you.
For example your response is NSData like below :
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
NSMutableDictionary *_dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
NSString *Success = [_dict valueForKey:#"success"];
You will get your desire output in Success.

Use NSJSONSerialization to get an NSMutableDictionary, check if success is true (YES), and if so, get the URL. E.g., the following should result in URL: www.mydomain.com being output to the debug window:
NSString *jsonString = #"{\"success\":true,\"domains\":[{\"URL\":\"www.mydomain.com\",\"name\":\"Test Alpha\",\"id\":\"100\"}]}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
BOOL success = [dictionary objectForKey:#"success"];
if (success) {
NSMutableArray *array = [dictionary objectForKey:#"domains"];
NSMutableDictionary *domainsDictionary = [array firstObject];
NSString *urlString = [domainsDictionary objectForKey:#"URL"];
NSLog(#"URL: %#", urlString);
}

Related

iOS fetching json object from json string

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

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

Having Trouble Parsing JSON

So I've created a service call, and as of now it is working. This is the link to the URL which you must see to be able to help me:
http://jobs.github.com/positions.json?description=python&location=new+york
For some reason, my code here isn't able to retrieve the dictionary objects of the data. It returns SIGABRT.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = #"http://jobs.github.com/positions.json?description=python&location=new+york";
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *jobs = json[#" "];
for (NSDictionary *theJob in jobs)
{
NSLog(#"%#", theJob[#"description"]);
}
}
Your JSON is an array of dictionaries. Change
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *jobs = json[#" "];
to
NSArray *jobs = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

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