Need to prefix JSON document being generated from NSMutableDictionary in iOS - ios

I am able to successfully generate a JSON document by iterating through a NSMutableDictionary. This NSMutableDictionary in turn, contains two values that are also NSMutableDictionary's, the keys of which are reports, and results respectively.
The code that constructs the JSON document is as follows:
NSMutableDictionary *jsonDoc = [NSMutableDictionary dictionary];
[jsonDoc setObject:results forKey:#"results"];
[jsonDoc setObject:reports forKey:#"reports"];
NSError *ierror = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDoc options:NSJSONWritingPrettyPrinted error:&ierror];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Output: %#", jsonString);
and my JSON output looks like this:
JSON Output: {
"results" : [
{
"date" : "2012-12-25T16:58:25",
"name" : "Test 1",
"result" : "Fail"
},
{
"date" : "2012-12-25T16:58:33",
"name" : "Test 2",
"result" : "Pass"
},
{
"date" : "2012-12-25T16:58:38",
"name" : "Test 3",
"result" : "Pass"
},
{
"date" : "2012-12-25T16:58:45",
"name" : "Test 4",
"result" : "Fail"
}
],
"reports" : [
]
}
I am very happy with the output I am getting. However, what I would like to do now is to prefix the data I am outputting with additional details that would go after the JSON Output: { but before "results". The additional details are simply NSString values like "Name:", "Address", "City", "Province", "Postal Code", etc. How would I do this given the code structure that I have presently? The catch is that I would like these details to be part of the original JSON object when I am initially building the JSON object, and not simply when I am outputting to the console.

Just call setObject:forKey: for each of the key/value pairs you want to add to the jsonDoc dictionary. It doesn't matter whether you put them above or below the two calls you have in your question since dictionaries are unordered.

Related

Order of json format is getting changed

Order of json format is getting changed. I need the below format
{
"user_id": "",
"name": "",
"StDate": "07/16/2015 13:00",
"EdDate": "07/16/2015 13:00",
"detailed": [
{
"Stname": ""
},
]
}
What i am getting atlast is
{
"user_id" : "1",
"Detailed" : [
{
“Stname" : ""
},
"EdDate" : "08\/19\/2015 12:25:47",
"StDate" : "08\/19\/2015 12:25:47",
“name” : "",
}
After getting all values i am converting to json. I am using the following code.
NSError *error1;
NSString *jsonString1;
NSData *jsonData1 = [NSJSONSerialization dataWithJSONObject:dictjson1
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData1) {
NSLog(#"Got an error: %#", error1);
} else {
jsonString1 = [[NSString alloc] initWithData:jsonData1 encoding:NSUTF8StringEncoding];
NSLog(#"converted json string is %#",jsonString1);
}
Please advice.
JSON has two structures: objects and arrays. Arrays are indexed by integers, and ordered. Objects are indexed by strings, and unordered. You can't enforce order on JSON objects; it is implementation-dependent. If you need to access object attributes in a certain order, enumerate the keys in this order in an array.

How to create a NSDictionary with blank key/ without key for an object

I want to create a JSON string from a NSDictionary.The complete JSON to create is given below.
{
"source":"point a ",
"destination":"point b ",
"boardingPoint":{
"id":"2222",
"location":"Some location"
},
"customerName":"test",
"customerLastName":"testing",
"customerEmail":"test#gmail.com",
"blockSeatPaxDetails":[
{
"age":"20",
"name":"test123",
"sex":"M",
"title":"Mr",
"email":"testing#gmail.com"
}
],
"inventory":0
}
Now I am stuck at creating dictionary for the first part of this JSON ie
{
"source": "point a ",
"destination": "point b ",
"boardingPoint": {
"id": "2222",
"location": "Some location",
},
Here the boardingPoint is a dictionary which is added to one dictionary.And then along with rest of the keys I make a final dictionary.So when I create the final dictionary, with objectsAndKeys I have no key to set for the first part which is shown below.If I set blank like this #" " the JSON string shows " " as key.And ofcourse I cannot use nil.How to do it then?
This is how it apppears if I insert blank as key for the first part
{
"" : {
"source" : "point a",
"boardingPoint" : {
"id" : "2222",
"location" : "Some location",
},
"destination" : "point b"
},
This is how I create the dictionaries
NSDictionary *boardingPoint = [NSDictionary dictionaryWithObjectsAndKeys:boardingPointID,#"id", boardingLocation,#"location",nil];
NSDictionary *firstDictionary = [NSDictionary dictionaryWithObjectsAndKeys:source,#"source",dest,#"destination",nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithObjectsAndKeys:firstDictionary, #" ",customerName,#"customerName",customerLastName,#"customerLastName",customerEmail,#"customerEmail",blockSeatPaxDetails,#"blockSeatPaxDetails",inventory,#"inventory",nil];
and then ofcourse
NSData *finalData = [NSJSONSerialization dataWithJSONObject:mainDictionary options:NSJSONWritingPrettyPrinted error:nil];
The first part of your JSON, properly indented, is:
{
"source":"point a ",
"destination":"point b ",
"boardingPoint":{
"id":"2222",
"location":"Some location",
},
"customerName":"test",
"customerLastName":"testing",
"customerEmail":"test#gmail.com",
"blockSeatPaxDetails":[
{
"age":"20",
"name":"test123",
"sex":"M",
"title":"Mr",
"email":"testing#gmail.com",
},
(You've apparently elided something toward the end so I can't slow the last few lines.)
There is no "missing key" or anything of the sort. If you feed your (unelided) JSON through NSJSONSerialization it will produce the correct "tree" of dictionaries and arrays.

sqlite command in iOS

Here I am using Sqlite Database for my Application, and my Database Table contains the column keyjson and values in rows are like below
{"filename":"21-01-3-02","label":""}
{"filename":"02-C-4-1","label":"17"}
{"filename":"14-L-3-2","label":"Nord Est"}
{"filename":"02-Z-5-1NouvelleIndustrieSectionValton","label":"1810"}
json data sas string
now I need to particular string that like
02
1
2
1NouvelleIndustrieSectionValton
from that particular column .
can anyone know the query for it,
Please replay me
&regards
You can do that without SQLite query. First, convert your JSON to a NSMutableArray :
NSData *data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
Then you can parse it easily as follow :
NSMutableArray *finalResult = [NSMutableArray array];
NSString *filename;
for (id e in res){
filename = [e objectForKey:#"filename"];
[finalResult addObject:[[filename componentsSeparatedByString:#"-"] lastObject]];
}
// Here we go, finalResult contains the values you want
The problem is that your "JSON" is not valid JSON. It should look like this if you want it works :
[
{
"filename": "21-01-3-02",
"label": ""
},
{
"filename": "02-C-4-1",
"label": "17"
},
{
"filename": "14-L-3-2",
"label": "Nord Est"
},
{
"filename": "02-Z-5-1NouvelleIndustrieSectionValton",
"label": "1810"
}
]

Creating JSON file using NSDictionary with an array

I am attempting to create json data to send to a server via an HTTP POST request. The server will only accept a specific format of JSON, otherwise it will return an error. I can successfully create and upload the JSON file to the server, however I am getting the following error because I have not formatted my JSON incorrectly:
JSON Error Message: {
code = "-2";
message = "Validation error: {\"message\":{\"to\":[\"Please enter an array\"]}}";
name = ValidationError;
status = error;
}
As you can see, the server needs a complex JSON format with an Array of Values and Keys but I'm not sure how to do that. Below is my current code to create the JSON data:
//Create Array With TO Values
NSDictionary *toField = #{#"email" : emailField.text};
//Create Dictionary Values
NSDictionary *messageContent = #{#"subject" : #"APPNAME Registration Complete", #"from_email" : #"email#domain.com", #"to" : toField};
NSDictionary *mandrillValues = #{#"key" : #"APPKEY",
#"redirect_url" : #"PRIVATE-URL",
#"template_name" : #"app-registration",
#"template_content" : [NSNull null],
#"message" : messageContent
};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:mandrillValues options:NSJSONWritingPrettyPrinted error:nil];
According to the server, I need an array with keys and values, similar to a nsdictionary. When I use an NSArray, though, I can't add values / keys. Any ideas on how I should go about doing this? Below is an example of the JSON format that the server will accept, am I doing everything right to follow this format? If not, what do I need to change to match the format?
{
"key": "example key",
"template_name": "example template_name",
"template_content": [
{
"name": "example name",
"content": "example content"
}
],
"message": {
"text": "example text",
"subject": "example subject",
"from_email": "message.from_email#example.com",
"from_name": "example from_name",
"to": [
{
"email": "example email",
"name": "example name"
}
],
}}
Looks like the "to" field expects an array. Unless the variable toField is an NSArray that contains dictionaries with keys and values as described, you're going to get a JSON that's not exactly like the one you want.
I would suggest outputting the description of the outgoing JSON to see exactly where there are differences.
Update
I saw the addition to your question -
NSDictionary *toField = #{#"email" : emailField.text};
Does not create an array. Try:
NSArray *toField = #[#{#"email" : emailField.text}];

ios json parsing sub collection

I have a json collection I am able to parse perfectly fine 1 level deep, but each item in the main collection has a collection in it. I am not quite sure how to access 'item' to get the sub collection like I did with the main collection...
NSString *response = [request responseString];
NSDictionary *json = [response JSONValue];
NSArray *items = [json valueForKeyPath:#"item"];
for (id item in items)
{
mainObject.name = [item objectForKey:#"name"]; //this works fine
// How do I get sub collection from item?
}
Some of the json:
{"item":
{
"available_at" : null,
"created_at" : "2011-12-09T19:52:23Z",
"lo_id" : 30,
"id" : 24,
"merchant_id" : 1,
"order_id" : 25,
"reach_local_link" : null,
"status" : null,
"token" : "12-258847891-1",
"updated_at" : "2011-12-09T19:52:23Z",
"url" : "api/dir/v1/item/12-258847891-1/print",
"subitem1" :
{
"area" : "local",
"broker_id" : "",
"broker_id" : null,
"category" :
{
"category":....
In the example, there could be multiple sub items like subitem1. I need to get the collection of those and have another for loop inside the current one.
item will simply be a dictionary or array if it is one in the JSON object. For example, you should be able to do this:
NSDictionary *subitem1 = [item objectForKey:#"subitem1"];
It's simply a NSDictionary in there, so you can use it as one.
I really recommend logging the Objective-C representation of your JSON object, it makes it easier to work with it:
NSLog(#"%#", json);
Warning
It's strongly recommended to check the type of the objects you load before assuming that they really are dictionaries, strings or arrays. If they aren't, you'll notice that your application is going to crash.

Resources