How to create a json array from these json objects in iOS - ios

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

Related

Convert JSON array to Objective-C in iOS

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

how to parse this json data in ios7

The code:
NSURL * url=[NSURL URLWithString:#"alamghareeb.com/mobileData.ashx?catid=0&No=10"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSMutableArray * referanceArray=[[NSMutableArray alloc]init];
NSMutableArray * periodArray=[[NSMutableArray alloc]init];
NSArray * responseArr = [NSArray arrayWithArray:json[#"item"]];
for (NSDictionary * dict in responseArr) {
[referanceArray addObject:[dict objectForKey:#"created"]];
}
The JSON looks like:
{
"item" = [
{
"id" : "2292",
"created" : "10/01/2015 10:21:18 ص",
"title" : "الإمارات: ملابس رياضية فاخرة لتحسين أداء الإبل في السباقات ",
"image_url" : "http://alamghareeb.com/Photos/L63556482078696289044.jpg",
"image_caption" : ""
},
{
"id" : "2291",
"created" : "10/01/2015 09:28:11 ص",
"title" : "طبيبة تجميل 'مزورة' تحقن مرضاها بالغراء والاسمنت",
"image_url" : "http://alamghareeb.com/Photos/L63556478891290039015.jpg",
"image_caption" : ""
}
]
}
This JSON is not valid. Did you build it manually? The "item" = ... should be "item" : ....
In the future, you can run your JSON through http://jsonlint.com to verify any issues. Likewise, you should add error checking in your Objective-C code, e.g.
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
if (!json) {
NSLog(#"JSON parsing error: %#", error);
}
I'd also suggest changing your server code to not build JSON manually, but take advantage of JSON functions (e.g. if PHP, build associative arrays and then generate JSON output using the json_encode function).
So, once you fix the JSON error, to parse the results might look like:
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!dictionary) {
NSLog(#"NSJSONSerialization error: %#", error);
return;
}
NSArray *items = dictionary[#"item"];
for (NSDictionary *item in items) {
NSString *identifier = item[#"id"];
NSString *created = item[#"created"];
NSString *title = item[#"title"];
NSString *urlString = item[#"image_url"];
NSString *caption = item[#"image_caption"];
NSLog(#"identifier = %#", identifier);
NSLog(#"created = %#", created);
NSLog(#"title = %#", title);
NSLog(#"urlString = %#", urlString);
NSLog(#"caption = %#", caption);
}
You can use NSJSONSerialization. No need to import any class.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[strResult dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
or use NSData directly as
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:theJSONDataFromTheRequest options:0 error:nil];
Source : Stackoveflow question

iOS is creating a JSON String without {} -- only has [ ]?

Why is the assignment to jsonString not including braces{}?
Here's what I'm getting:
["anemail#chdr.com"]
CODE
if (_allEmails)
{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_allEmails options:0 error:&error];
if (!error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[dictionary setObject:jsonString forKey:#"AllEmails"];
}
}
The _allEmails variable must be an array (you tell me) and for braces you need to store your data in a dictionary.
Perhaps what you're looking for is:
if ([_allEmails count] > 0)
{
NSError *error = nil;
NSDictionary *dict = #{ #"AllEmails" : _allEmails };
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
// Note: Check returned object and not NSError object
if (jsonData) {
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
// Do thing with string
} else {
NSLog(#"Failed to serialize JSON: %#", [error localizedDescription]);
}
}
Because a JSON array is not enclosed braces, and what you have above is a JSON array. A JSON "object" is enclosed in braces.

iOS Error Parsing JSON

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.

iOS - Nested NSDictionaries to NSArray

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

Resources