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.
Related
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];
I am using AFNetworking to retrieve information about the weather for a specific location, e.g:
http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}
I am using the AFNetworking framework but I am having the problems parsing some objects of the JSON.
If I have an NSDictionary with the MAIN object information from the JSON:
NSDictionay *main = [responseObject objectForKey:#"main"];
If I log the main NSDictionary I will get the following valid output:
"main":{
"temp":296.78;
"pressure":1011;
"humidity":69;
"temp_min":293.15;
"temp_max":299.82
};
Although if I create a NSDictionary containing the weather object I will get the following information whenever logging it to the console:
NSDictionay *weather = [responseObject objectForKey:#"weather"];
"weather":(
{
"id":801;
"main":"Clouds";
"description":"few clouds";
"icon":"02d"
}
);
The parsed information contains ( brackets instead of [ from the original response. This does not allow me to correctly access the inside attributes of the weather object.
Summing up, I am able to access all the inside variables of the MAIN object, but I cannot access the attributes of the Weather object (e.g access the icon attribute).
Can someone help me with this ?
Thank you,
You calling your service as below.
NSString *query = #"http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}";
NSLog(#"%#",query);
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
Now print Response :
NSLog(#"weather==%#",[results objectForKey:#"weather"]);
NSLog(#"description==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"description"]);
NSLog(#"icon==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"icon"]);
NSLog(#"id==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"id"]);
NSLog(#"main==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"main"]);
Your Response is :
whwather==(
{
description = "sky is clear";
icon = 01d;
id= 800;
main= Clear;
}
)
description== "sky is clear";
icon == 01d;
id == 800;
main == Clear;
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]);
How do we convert a NSDictionary into JSON data object? I want to send a JSON data to my server. I am using the below code but facing an issue when it comes to NSDictionary containing Array or further NSDictionary in it. This works well with simple key-value pair.
Issue: It fails on the below line and sets the error object. This works fine if I remove arrays and dictionaries from the source myData dictionary.
NSData *aPostBodyData = [NSJSONSerialization dataWithJSONObject:myData options:0 error:&error];
Where myData looks like:
{
URI = "www.google.com";
addOnTestString = "4,3,";
status = (
"In Progress",
Submitted,
Delivered
);
data =
{
URI = "www.test.com";
testString = "43";
status = (
"In Progress",
Submitted,
Delivered
);
}
}
Error trace:
ok i just write a sample code that includes your situation and it works well.
NSArray * myarray=#[#"a",#"b"];
NSMutableDictionary * dict=[[NSMutableDictionary alloc] initWithObjects:#[#"a",myarray] forKeys:#[#"str",#"arr" ]];
NSData * js=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsString=[[NSString alloc] initWithData:js encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsString);
probable reasons for you get errors may be;
your myData is not in type NSDictionary or NSArray.
or while adding arrays to dictionary you are missing a point.
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"];