My Json response is
[{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4"}]
And I did
NSString *response = [request responseString];
SBJSON *parser = [[SBJSON alloc] init];
NSArray *jsonObject = [parser objectWithString:response error:nil];
At this point I believe that jsonObject is a array that has two NSDictionary..
How can I make jsonObject that has two NSArray instead of NSDictionary?
What is the best way to do so? I think that I need to convert nested NSDictionary to NSArray?
I would use the NSJSONSerialization class now in the Foundation framework.
With the JSONObjectWithData method, it will return the type of container you want the data stored in at the top level. For example:
NSError *e;
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&e];
for (NSDictionary *dict in jsonObject) {
NSLog(#"json data:\n %#", dict);
// do stuff
}
Alternately, you could return a mutable container, such as:
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&e];
Here is the Apple documentation:
NSJSONSerialization
Related
I am new to iOS development. I am trying to covert JSOn array values to Objective-C values. My JSON values are like this:
{"result":
[{"alternative":
[{"transcript":"4"},
{"transcript":"four"},
{"transcript":"so"},
{"transcript":"who"}],
"final":true}],
"result_index":0}
I have tried it this way:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
speechArray is always null. How to resolvee this problem?
At the same time I would like to print transcript values.
I think the problem might be in initializing the array and Dictionary.
Try doing this,
NSDictionary *speechResult = [NSDictionary new];
NSArray *speechArray = [NSArray new];
Hope it helps..
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];//data is your response from server as NSData
if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
NSArray * speechArray = json[#"result"];
}
NSLog(#"speech array %#",speechArray);
Did you check the value in NSDictionary (speechResult).
If it is nil, check the json data isValid or not.
NSError *error;
if ([NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error] == nil)
{
// Check the error here
}else {
// here check whether it is a dictionary and it has key like #Bhadresh Mulsaniya mentioned.
}
If returns nil, then you check the error to understand what's wrong.
try this may be it will help you:-
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult = [NSDictionary new];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
try this code,
restaurantdictionary = [NSJSONSerialization JSONObjectWithData:mutableData options:NSJSONReadingMutableContainers error:&e];
NSMutableArray *main_array=[[NSMutableArray alloc]init];
main_array=[restaurantdictionary valueForKey:#"results"];
NSLog(#"main_array %#", main_array);
its working for me, hope its helpful
You have to initialize the array before using it,
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [[NSArray alloc] init];
speechArray= [speechResult valueForKey:#"result"];
if (speechArray.count>0) {
NSDictionary * alternativeDictn = [speechArray objectAtIndex:0];
NSArray *alternativeAry= [[NSArray alloc] init];
alternativeAry = [alternativeDictn objectForKey:#"alternative"];
NSLog(#"%#",alternativeAry);
}
NSLog(#"Response is of type: %#", [speechArray class]);
Using this code you will get following result,
(
{
transcript = 4;
},
{
transcript = four;
},
{
transcript = so;
},
{
transcript = who;
}
)
Try out the below code to get the transcripts:
NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *responseObj = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSArray *responseArray = [responseObj objectForKey:#"result"];
for (NSDictionary *alternative in responseArray) {
NSArray *altArray = [alternative objectForKey:#"alternative"];
for (NSDictionary *transcript in altArray) {
NSLog(#"transcript : %#",[transcript objectForKey:#"transcript"]);
}
}
} else {
NSLog(#"Error in parsing JSON");
}
You should alloc your dictionary first like this-
NSDictionary *speechResult = [[NSDictionary alloc]init];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];
I have a dictionary that looks like this.
NSDictionary *dict = #{#"cpu" : self.proData ,
#"date" : timeMilliString,
#"memory" : self.memData,
#"battery" : self.batData,
#"deviceID" : #"1"
};
I'm creating json objects from it like this:
self.jsonObj1 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
self.jsonObj2 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
self.jsonObj3 = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
Afterwards I want to put the 3 json objects into a json array and then put that json array into another json object. So finally, it should look something like this:
{"mobileData":[
{ "cpu":-991,
"date":"142441374.5834",
"memory":978,
"battery":-96,
"deviceID" : 2
},
{ "cpu":-51,
"date":"142441374.5834",
"memory":978,
"battery":-96,
"deviceID" : 2
},
{ "cpu":-51,
"date":"142441374.5834",
"memory":978,
"battery":-96,
"deviceID" : 2
}
]
}
I have tried it as follows but it's not working.
NSArray *jsonArray = #[self.jsonObj1, self.jsonObj2, self.jsonObj3];
NSDictionary *dict = #{#"mobileData" : jsonArray};
if ([NSJSONSerialization isValidJSONObject:dict])
{
// Serialize the dictionary
json = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error2];
// If no errors, let's view the JSON
if (json != nil && error2 == nil)
{
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
//[jsonString release];
}
}
I'm getting an exception.
Any ideas? Thanks.
Firstly add all dictionaries to a array.
NSMutableArray *mutArrData = [NSMutableArray array];
//Add dictionaries which vary to your requirement.
[mutArrData addObject:yourDictionary]; //1
[mutArrData addObject:yourDictionary]; //2
[mutArrData addObject:yourDictionary]; //3
Now create a main dictionary to add array.
NSDictionary *dictJsonData = [NSDictionary dictionaryWithObjectsAndKeys:[mutArrData mutableCopy],#"mobileData",nil];
Now create json from dictionary
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJsonData options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", jsonString);
}
I am new to iOS. I have this JSON data that I needed to parse:
{
"allseries":[
{
"type":"HR",
"title":"Heart Rate",
"xLabel":"Time",
"yLabel":"Beats per Min",
"defaultUnit":"BPM",
"url":"info/info?user=admin%40korrent.com&type=HR",
"size":18,
"firstTs":1406755651,
"lastTs":1406841254
},
{
"type":"TEMP",
"title":"Temperature",
"xLabel":"Time",
"yLabel":"Temperature",
"defaultUnit":"F",
"url":"info/info?user=admin%40korrent.com&type=TEMP",
"size":6,
"firstTs":1406854147,
"lastTs":1406854283
}
],
"status":"OK"
}
So far this is my code:
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
NSData *jsonData = [dataReceived dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", [dict description]);
NSLog(#" %# ", dict[#"allseries"]);
NSString *jsonString=dict[#"allseries"];
if (_programState == 4){
NSLog(#"state is 4");
NSLog(#"%#",jsonString);
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
However, the code throws invalid argument exception for this line:
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Further more, jsonString seems totally "inoperable". I cannot split it, append strings to it etc. So what's wrong?
// The following two lines are just for logging and otherwise are not needed.
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
// Deserialize the JSON data into a dictionary
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: _responseData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", dict);
// Get the array from the dictionary element "allseries".
NSArray *jsonArray = dict[#"allseries"];
NSLog(#"jsonArray: %#", jsonArray);
Here jsonArray is the array of dictionaries for "allseries" from the JSON
What you did is totally, totally wrong.
dict[#allseries] is not an NSString. It is an NSArray with two elements, and both its elements are NSDictionary.
I'm having trouble parsing my JSON. The JSON is:
{"privatecode":"XDhUZQ1rA2gBZwshV2NrZQRnDmVPZQhuVj7WOlNrC29SPwg6VDUGelU1DahQNlc1AWpcPVBuWmc"}
I'm using following code:
id parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
The class of parsedObject is NSDictionary, but it contains the following error:
(<invalid>) [0] = <error: expected ']'
error: 1 errors parsing expression
>
Of course I could say:
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
but this makes no difference. I just want to get the privatecode as an NSString object, so what am I doing wrong and how can I fix this?
Many thanks in advance.
EDIT: Some more code I'm using:
NSLog(#"Response: %#", [request responseString]);
id parsedObject = [NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:&localError];
request is of type ASIHTTPRequest. The output of the log is:
Response: {"privatecode":"XDhUZQ1rA2gBZwshV2NrZQRnDmVPZQhuVj7WOlNrC29SPwg6VDUGelU1DahQNlc1AWpcPVBuWmc"}
Use this:
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&localError];
I am using this for my project without any problem. Hope this helps. :)
EDIT:
From your error it seems that it is an array (array starts with '['). But your posted JSON is Dictionary (starts with '{'). It is weird. I searched and got this. Check this:
if ([returnedFromWeb respondsToSelector:#selector(objectAtIndex:)]) { // you can replace respondsToSelector:#selector(objectAtIndex:) by isKindOfClass:[NSArray class]
//it's an array do array things.
} else {
//it's a dictionary do dictionary things.
}
This worked for me, I was getting the same error you are but my response is an array. Since it looks like you are expecting a dictionary I'll include what that might look like.
id test = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:error];
NSArray *array;
NSDictionary *dictionary;
if ([test isKindOfClass:[NSArray class]]) {
//it's an array do array things.
array = [NSArray arrayWithArray:test];
} else {
//it's a dictionary do dictionary things.
dictionary = [NSDictionary dictionaryWithDictionary:test];
}
At this point you should be able to access the contents of the array or dictionary.
Simplified:
NSArray *array = [NSArray arrayWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:error]];
OR
NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:error]];
I'm new to JSON and don't understand why this is failing. The JSON is valid according to on-line validation tools, but NSJSONSerilization says this the string is invalid. Why is it invalid?
NSString* JSON = #"{\"Questionnaire\":{\"questionnaireid\":1,\"modifiedDate\":\"2012-12-28 15:27:00\"}}";
if (![NSJSONSerialization isValidJSONObject:JSON]) {
return nil;
}
NSError *jsonParsingError = nil;
NSDictionary* data = [NSJSONSerialization dataWithJSONObject:JSON options:NSJSONReadingMutableContainers error:&jsonParsingError];
why you did serialization when you already created JSON yourself ?
What you should do:
NSData *jsonPayload = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonPayload
options:kNilOptions error:&error];
Because a JSON Object must be of type NSArray or a NSDictionary while you are passing a NSString.
From the docs:
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
UPDATE
You probably want to do this:
NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];