Having Trouble Parsing JSON - ios

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

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

get object from json string in iOS - Xcode

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

Using NSArray and NSDictionary to access a JSON object without a root element

Here's an example of my data:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
I'm trying to retrieve the value for last_price by loading the contents of my NSDictionary into an Array.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
self.darkPosts = [NSMutableArray array];
NSArray *darkPostArray = [darkDict objectForKey:#""];
for (NSDictionary *darkDict in darkPostArray) {...
But my json doesn't have a root element, so what do I do?
Additionally, when using the suggested answer, the output is ("...
- (void)viewDidLoad{
[super viewDidLoad];
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSString *lastP = [darkDict valueForKey:#"last_price"];
self.dark_label.text = [NSString stringWithFormat: #"%#", lastP];
}
It looks like you are wanting to iterate over your results. The root element is an array not a dictionary so you can just start iterating
NSError *error = nil;
NSArray *items = [NSJSONSerialization JSONObjectWithData:darkData
options:kNilOptions
error:&error];
if (!items) {
NSLog(#"JSONSerialization error %#", error.localizedDescription);
}
for (NSDictionary *item in items) {
NSLog(#"last_price => %#", item[#"last_price"]);
}
If you literally just want to collect an array of the last_price's then you can so this
NSArray *lastPrices = [items valueForKey:#"last_price"];
Convert the JSON to an NSArray with NSJSONSerialization. Then access the value:
NSData *darkData = [#"[{\"code\":\"DRK\",\"exchange\": \"BTC\",\"last_price\": \"0.01790000\",\"yesterday_price\": \"0.01625007\",\"top_bid\": \"0.01790000\"}, {\"top_ask\": \"0.01833999\"}]" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:darkData
options:0
error:&error];
NSString *value = array[0][#"last_price"];
NSLog(#"value: %#", value);
NSLog output:
value: 0.01790000
If you are having trouble post the code you have written to get some help.
-- updated for new OP code:
The web service returns a JSON array or dictionaries not a JSON dictionary. First you have to index into the array and then index into the dictionary.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSArray *darkArray = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
NSLog(#"lastP: %#", lastP);
NSLog output:
lastP: 0.01970000
Note that the two lines:
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
can be replaced with the single line using array indexing:
NSString *lastP = darkArray[0][#"last_price"];
Where the "[0]" gets the first array element which is a NSDictionary and the "[#"last_price"]" gets the names item from the dictionary.

Resources