IOS : Get JSON Response from URL [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am trying to get data from this link and store it in NSArray
Format of the response:
data(
[
"Mumbai, MH, India",
"Mumford, NY, United States",
"Mumford, TX, United States",
"Navi Mumbai, MH, India",
"New Mumbai, MH, India"
]
)
Tried as like regular JSON response, but not getting any data.
Please help me...
Thanks in advance.

In your php may be return array value. so instead of that use json_encode and Returns the JSON representation of a value.
and use in Objective-C code like
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

I think this may be the problem ..
JSON that have array response will be [x, x, x, x, x]..
But your json is data([x, x, x, x, x]); That's why you are not getting correct response in jsonserialization.
NSArray *response = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
JSON that have dictionary response will be {key=data, key=data, key=data}
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Your json gets the following error when you try to convert
(JSON text did not start with array or object and option to allow fragments not set.)
Your json not meets both the format. Can you please check it and try

http://gd.geobytes.com/AutoCompleteCity?callback=data&q=mum
This is a JSONP response, which wraps json response in callback function data.
Remove callback parameter and try to parse again
http://gd.geobytes.com/AutoCompleteCity?q=mum
See also: What is JSONP all about?

Try with following code,
NSString *jsonString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *jsonDictionary = [jsonString JSONValue];
NSLog(#"%#", jsonDictionary);

That doesn't look like JSON to my eyes, but you might be able to pass that input to NSJSONSerializer (I'm thinking the JSONObjectWithData:options:error: API) and get an Objective-C object out of it

I think your response string meeting JSON qualification JSON string will look like this
{
"array": [
1,
2,
3
],
"boolean": true,
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
make sure that response is getting from service is JSON string

you can try this code.. this is not perfect.. but you can retrieve the data here.
NSError *err = Nil;
NSURL *url = [NSURL URLWithString:#"http://gd.geobytes.com/AutoCompleteCity?callback=data&q=mum"];
NSData *data1 = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&err];
NSLog(#"%#",data1);
NSString *json_string = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(#"%#",json_string);
NSString *json = [json_string substringFromIndex:4];
NSLog(#"%#",json);
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:#"()"];
NSString *json1 = [json stringByTrimmingCharactersInSet:charsToTrim];
NSLog(#"%#",json1);
if ([json1 length]> 0)
{
json1 = [json1 substringToIndex:[json1 length]-2];
}
NSLog(#"returnResponse %#",json1);
NSMutableArray *a = [[NSMutableArray alloc]init];
[a addObject:[json1 componentsSeparatedByString:#","]];
NSLog(#"%#",a);
NSLog(#"%#",[a objectAtIndex:0]);

Related

Creating a json object dynamically

I have to make json request of following type.
{
"documents": [
{
"file_size": 48597,
"file_name": "pisa-en.pdf",
"file_content": "base64String"
}
]
}
Following is the way how im creating the json.
NSString *json = [NSString stringWithFormat:#"{\"documents\": [ { \"file_size\": %#, \"file_name\": %#\", \"file_content\": \"%#\" } ]}",_imageSizeArray[0],_imageNameArray[0],_baseArray[0]];
but the problem is that, the documents array may even contain more than one json object within it. If thats the case How can i create a jsonobject dynamically and embed it within documents array?
You have to take Array and add document object in that array
than at request time you have to convert your array to json string by following code
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Escaped double-quotes appear in string during debugging

I have a dictionary and I need to generate a JSON string by using NSMutableArray. Here is my code:
NSDictionary *dict = #{
#"From":From,
#"To":To,
#"DepartureDate":DepartureDate,
};
[FinalArray addObject:dict];
Then I generate the JSON String like this:
NSError *error;
NSData * JSONData = [NSJSONSerialization dataWithJSONObject:FinalArray
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
NSLog(#"jsonData=%#", jsonString);
Now output is on NSLog like this:
[
{
"From": "city",
"To": "city",
"DepartureDate": "20160301"
}
]
But while I'm debugging, at a breakpoint, the string appears with escaped double-quotes:
"[{\"From\":\"city\",\"To\":\"city\",\"DepartureDate\":\"20160301\"}]"
Why is that?
That's a stringified json object. My guess is that to allow the json to be shown in the console it's stringified, adding the escaped quotes. In your runtime the backslashes don't exist, they are only there to correctly display the json in the console.

Converting NSString to proper JSON format

Converting NSString to proper JSON format..
NSString *input_json = [NSString stringWithFormat:#"{\"id\":\"%#\",\"seconds\":\"%d\",\"buttons\": \"%#\"}", reco_id, interactionTime, json_Buttons];
Here json_Button is in json format converted from nsdictionary..
My input_json result is:
{"id":"119","seconds":"10","buttons": "{
"update" : "2",
"scan" : "4"
}"}
It is not in a proper JSON format. key buttons contain "{}" I want to remove these quotes.
Expected Result is:
{
"id": "119",
"seconds": "10",
"buttons": {
"update": "2",
"scan": "4"
}
}
You are going about this all wrong. First, create an NSDictionary that contains all of the data you want converted to JSON. Then use NSJSONSerialization to properly convert the dictionary to JSON.
Something like this will work:
NSDictionary *dictionary = #{ #"id" : reco_id, #"seconds" : #(interactionTime), #"buttons" : json_Buttons };
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if (data) {
NSString *jsonString = [[NSString alloc] intWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
} else {
NSLog(#"Unable to convert dictionary to JSON: %#", error);
}
It's a bad idea to try to build JSON strings manually. Use the NSJSONSerialization class. That makes it easy. Create your dictionary, then call dataWithJSONObject:options:error:.
If you use options: NSJSONWritingPrettyPrinted it inserts line breaks and whitespace that makes the JSON more readable.
By using that function you get correctly formatted JSON every time, and it's flexible because if you send it a different dictionary you get different JSON.

reading a json object from a website in objective c

I need to separate sub person, name, age, home addr, office addr from below given json object retrieved from a website
{ "person" :
[{"subperson":{"home":{"id":"kljljk"},"name":"person3","age":"18","addr":{"home addr":"ksdjr","office addr":"kjshdg"}}}]}
tried nsjsonserialization,sbjson and touchJSON api's. returns a dictionary in which person is the key and everything else is the value(format of json string specified below the code)
my code:
NSURLRequest *urlreq = [NSURLRequest requestWithURL:url];
NSData *response = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
[webviv loadRequest:urlreq];
SBJsonParser *jsonparser = [SBJsonParser new];
NSDictionary *json = [jsonparser objectWithData:response];
NSLog(#"%#\n", json);
for(id key in json)
{
NSLog(#"%#=%#",key,[json objectWithKey: key]);
}
//output is
person = (everythingelse starting with [, can't separate name and other required things)
//using NSJSONSerialization
if ([NSJSONSerialization JSONObjectWithData:response options:0 error:&error])
{
NSLog(#"json");
}
NSData *pTL = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSLog(#"%#",pTL);
//Output is the same
//for(int i=0;i<[pTL count];i++)
//{
//NSLog(#"%d",i);
//}
//even with for loop the output is the same
Tell your backend guys(the person who wrote this web service) to change "[" as "(" and "]" as")". ( is array { is dictionary. [ is nothing for us we can differentiate it
There is a problem with your JSON structure.
For instance, the following is not a legal JSON string:
"subperson":"home":{"id":"kljljk"}
Try replacing it with the following:
{"person":[{"subperson":{"id":"kljljk","name":"person3","age":"18","addr":{"homeaddr":"ksdjr","office addr":"kjshdg"}}}]}
You can use any kind of online JSON parser tool to verify the JSON structure before continuing to debug your code.
Also you should read a little about JSON syntax here.

Understand and use this JSON data in iOS

I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];

Resources