Order of json format is getting changed - ios

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.

Related

How to parse Dynamic changes in json value. Dictionary with 2 nested dic & then array and then dic again

Dictionary with two nested dictionary and then array and then dictionary again how can i write code generally for objective c ,iOS 8;
{
"brands": {
"Clinique": {
"Foundation": {
"Even Better Makeup SPF 15": {
"productName": "Even Better Makeup SPF 15",
"colors": [
{
"id": "30816",
"client_id": "1422956000sjdaC",
"product_id": "190",
"shade_name": "Alabaster",
"shade_code": "#F0C9AE",
"color_id": null,
"image_url": "",
"price": "",
"offer": "",
"created_by": "1422956000sjdaC",
"created_date": "2015-03-06",
"sku_id": "",
"product_web_url": "",
"brand_id": "Clinique",
"product_name": "Even Better Makeup SPF 15",
"makeup_type": "Foundation",
"color_family": "cool"
},
As I can see, your JSON response is sending Product details, so the
"brands": {
"Clinique": {
"Foundation": {
will remain same always, and the response below it will change according to products.
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *productsDict = [[jsonDictionary objectForKey:#"brands"] objectForKey:#"Clinique"] objectForKey:#"Foundation"];
NSArray *keys=[productsDict allKeys];
for (int i = 0; i < keys.count; i++) {
NSDictionary *prodSingle = [productsDict objectForKey:[NSString StringWithFormat:#"%#",keys[i]]];
}
Now you have prodSingle, use this to get data of each product.
Note: Untested, I'll provide a tested version if this doesn't work.
EDIT:
As you said only brands key will remain constant and other will change dynamically,
you should do this :
So what you can do is create a NSDictionary with jsonData(response data) like this:
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
create a dictionary of brands
NSDictionary *brandsDict = [jsonDictionary objectForKey:#"brands"];
Now get all the keys:
NSArray *keys= [brandsDict allKeys];
Now use each key you got in Array to fetch data accordingly.

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

Xcode - Getting object out of an array within an array

I have a JSON array(dictionary?) of objects that are themselves an array. I need to find a value within one of these arrays so that I can compare it later. Part of my JSON data:
[
{
"Name": "Exhibitor",
"Url": "api/congress/exhibitor",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Workshop",
"Url": "api/congress/workshop",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Speaker",
"Url": "api/congress/Speaker",
"ResourceType": "Data",
"LastMod": 1389106977
},
]
My method receives a table name as a parameter and returns a time stamp. How would I receive the time stamp (1389106977) for the table "workshop" for example? This seems so simple but I cannot work it out for 'nested' arrays/dictionaries.
Thanks,
edit:
This is the my code with trojanfoe's added to it.
NSError* localError;
NSMutableArray *syncDataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (syncDataArray)
{
NSNumber *lastMod = nil;
for (NSDictionary *dict in syncDataArray)
{
NSLog(#"current table is: %#", dict[#"Name"]);
if ([tableName isEqualToString:dict[#"Name"]])
{
lastMod = dict[#"LastMod"];
//break;
}
}
NSLog(#"LastMod = %#", lastMod);
}
else
{
NSLog(#"syncDataArray is empty");
}
This works perfectly and makes sense
The JSON data looks like an array of dictionaries, so you can iterate over the array and test for the "Name" entry:
NSArray *jsonData = ...; // You have converted JSON to Objective-C objects already
NSNumber *lastMod = nul;
for (NSDictionary *dict in jsonData) {
if ([#"Workshop" isEqualToString:dict[#"Name"]]) {
lastMod = dict[#"LastMod"];
break;
}
}
if (lastMod) {
// You found it
}
(Note I am not certain the type of object used to store the "LastMod" object, so you might need to do some debugging to find out).
EDIT If you make extensive use of this data you should immediately convert the JSON data into an array of (custom) model objects, which will make it easier to manipulate the data as your app becomes more complex.
You have an array for dictionaries so it would look something like :
NSNumber *timestamp = [[JSON objectAtIndex:index] objectForKey:#"LastMod"];
NSNumber *timestamp = response[1][#"LastMod"];

how to get JSON object from server as it (in the same order) iPhone

Is there any way to get JSON object from the server in the same order??
For example when i fitch using browser my JSON object return like this:
{
"23": {
"numberOfRecords": "3",
"startDate": "27/11/2013",
"endDate": "31/12/2014",
"question": "How do you rate the new MenaME Portal ?",
"voteScale": "5",
"questions": {
"option1": {
"value": "1",
"option": "Poor",
"voteResult": "50.000"
},
"option2": {
"value": "2",
"option": "Acceptable",
"voteResult": "0.000"
},
"option3": {
"value": "3",
"option": "Good",
"voteResult": "0.000"
},
"option4": {
"value": "4",
"option": "Very Good",
"voteResult": "0.000"
},
"option5": {
"value": "5",
"option": "Excellent",
"voteResult": "50.000"
}
},
"selectedAnswer": "0",
"voteAnswered": "0",
"votes": "6"
}
}
after parsing it with [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error]
the object returned like this :
{
23 = {
endDate = "31/12/2014";
numberOfRecords = 3;
question = "How do you rate the new MenaME Portal ?";
questions = {
option1 = {
option = Poor;
value = 1;
voteResult = "50.000";
};
option2 = {
option = Acceptable;
value = 2;
voteResult = "0.000";
};
option3 = {
option = Good;
value = 3;
voteResult = "0.000";
};
option4 = {
option = "Very Good";
value = 4;
voteResult = "0.000";
};
option5 = {
option = Excellent;
value = 5;
voteResult = "50.000";
};
};
selectedAnswer = 0;
startDate = "27/11/2013";
voteAnswered = 0;
voteScale = 5;
votes = 6;
};
}
Is there any way or framework to get the object as it (in the same order returned from the server) ??
Dictionaries, both in JSON and NSDictionary, are unordered, meaning that it is irrelevant which order you see things in the log. This is defined in the JSON specification and the documentation for NSDictionary.
If it actually matters what order things are displayed in, then either the API you are linking to isn't using correct JSON, or you're doing something wrong in your app. To help with those situations you can use several of the sorted NSDictionary implementations that are around.
Can I ask why you want to ensure the dictionary is maintained in the correct order?
I understand in some cases (mine) an ancient JSON -> XML web service was being called by my app and the client refused to adjust the service so it could accept unordered JSON (valid json) but if you're writing the app, why do you need to ensure that it is in order?
I have a NSMutableDictionary subclass that keeps objects added by setObject:forKey in the order you call the method that can be found here.
It works by storing a NSMutableOrderedSet of keys within the dictionary and then overrides the keyEnumerator method to return an enumerator based on the ordered set
- (NSEnumerator *)keyEnumerator
{
return [self.orderedSetOfKeys objectEnumerator];
}
You could modify the NSMutableDictionary subclass i created to expose the NSMutableOrderedSet in the public header and then modify this set yourself to get an ordered version of your dictionary.. For example:
NSDictionary *JSONWebServiceDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
LNOrderedMutableDictionary *orderedDictionary = [[LNOrderedMutableDictionary alloc] initWithDictionary:JSONWebServiceDictionary];
NSMutableOrderedSet *order = [[NSMutableOrderedSet alloc] initWithArray:#[#"key1",#"key2",#"key3"]]; //All the keys you are expecting and the order you want them in..
orderedDictionary.orderSet = order; //orderSet does not exist.. it is currently called `array` and not exposed in LNOrderedMutableDictionary.h
I haven't tested the code above but unless you want to create or modify an existing JSON parser then it seems that it is your only option..
If you did want to modify an existing parser then it might just be as simple as replacing dictionary instances with LNOrderedMutableDictionary to keep everything in order.
Another idea to expand the above sample code could be to replace
NSMutableOrderedSet *order = [[NSMutableOrderedSet alloc] initWithArray:#[#"key1",#"key2",#"key3"]];
with an array returned in the JSONWebServiceDictionary dictionary as arrays keep their order when parsed from JSON so maybe you could do this?
NSMutableOrderedSet *order = [[NSMutableOrderedSet alloc] initWithArray:[JSONWebServiceDictionary objectForKey:#"keyOrderArray"]]];
Look at what you have. If you test the result you got back from JSONObjectWithData (which we'll assume was declared as id jsonObject)
if ([jsonObject isKindOfClass:[NSDictionary class]) { ...
or
NSLog(#"The object type is %#", [jsonObject class]);
you will find that it is indeed an NSDictionary (or perhaps an NSMutableDictionary). That dictionary, as you can see from the dump (or infer from the nearly identical JSON) contains a single entry with a key of "23".
So let's cast the jsonObject to an NSDictionary and reference it:
NSDictionary* jsonDict = (NSDictionary*) jsonObject;
NSDictionary* entry23Dict = [jsonDict objectForKey:#"23"];
Now, if you NSLog entry23Dict you will discover it contains all of the above, absent the { 23 = ... } outermost dictionary.
You can then access, say, "questions" with
NSDictionary* questDict = [entry23Dict objectForKey:#"questions"];
From there the individual "option1", "option2", ... "option5" dictionaries can be accessed in a similar fashion. You simply proceed one layer at a time -- don't get overwhelmed by the entire structure. (It's often helpful, when you're first learning, to NSLog each "layer" as you "peel" it out of the containing structure.)
And, of course, you have all the standard facilities that are available to NSDictionary objects (and NSArray objects, should your JSON contain any [..] arrays). For instance, you can iterate on the keys of the dictionary with
for (NSString* key in jsonDict) {
NSLog(#"This entry's number is %#", key); // For the above will print "23"
NSDictionary* numberedDict = jsonDict[key]; // Using the "new" form of dictionary access
NSString* endDate = numberedDict[#"endDate"]; // Ditto
NSLog(#"The end date is %#", endDate);
}
This is a fairly common problem. It's also probably the most annoying part about iOS. (java doesn't have this issue at all). If you want to get back objects, take a look at restkit.org Specifically this answer may help: https://stackoverflow.com/a/8284343/836450

Need to prefix JSON document being generated from NSMutableDictionary in 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.

Resources