How to generate JSON programmatically using JSON framework for iPhone - ios

I am creating an application in that I need to send a JSON to the server to get some response.
How to generate JSON using JSON Framework for iPhone?
What are the other possible ways?

Create an array or dictionary of objects representing the information you want to send via JSON. Having done that, send -JSONRepresentation to the array/dictionary. That method returns a JSON string, and you send it to the server.
For instance:
NSDictionary *o1 = [NSDictionary dictionaryWithObjectsAndKeys:
#"some value", #"key1",
#"another value", #"key2",
nil];
NSDictionary *o2 = [NSDictionary dictionaryWithObjectsAndKeys:
#"yet another value", #"key1",
#"some other value", #"key2",
nil];
NSArray *array = [NSArray arrayWithObjects:o1, o2, nil];
NSString *jsonString = [array JSONRepresentation];
// send jsonString to the server
After executing the code above, jsonString contains:
[
{
"key1": "some value",
"key2": "another value"
},
{
"key1": "yet another value",
"key2": "some other value"
}
]

Create an NSMutableDictionary or NSMutableArray and populate it with NSNumbers and NSStrings. Call [<myObject> JSONRepresentation] to return a JSON string.
eg:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:#"Sam" forKey:#"name"];
[dict setObject:[NSNumber numberWithInt:50000] forKey:#"reputation"];
NSString *jsonString = [dict JSONRepresentation];

Related

NSDictionary format

Can anybody help me create an NSDictionary format of the following structure:
{
key1 = "value1";
key2 = "value2";
key3 = [
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
}
];
}
Try this code it might help you.
NSDictionary *dicationary = #{
#"key1":#"value1",
#"key2":#"value2",
#"key3":#[#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"}]
};
There is API in obj-c to convert Json to nsdictionary .I guess you should try that :
First convert json to nsdata (assuming you above JSON is in string format)
2.Then you API to convert that to NSDictionary :
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Just to answer your question about converting that JSON data to NSDictionary, here it is:
(assuming you already got your JSON data)
// add the first 2 VALUES with it's KEYS
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:VALUE1 forKey:KEY1];
[mainDict setValue:VALUE2 forKey:KEY2];
// then for the last KEY, create a mutable array where you will store your sub dictionaries
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY1];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY2];
[ma addObject:subDict];
// then add that array to your main dictionary
[mainDict setValue:ma forKey:KEY3];
// check the output
NSLog(#"mainDict : %#", mainDict);
// SAMPLE DATA - Test this if this is what you want
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:#"value1" forKey:#"key1"];
[mainDict setValue:#"value2" forKey:#"key2"];
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:#"subValue1" forKey:#"subKey1"];
[subDict setValue:#"subValue2" forKey:#"subKey2"];
[ma addObject:subDict];
[mainDict setValue:ma forKey:#"key3"];
NSLog(#"mainDict : %#", mainDict);
The following should work for you:
NSString *jsonString = #"{\"ID\":{\"Content\":268,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonDict[#"ID"][#"Content"]);
Will return you:
268

How to set NSString value to NSMutable dictionary?

I am implementing web-service APIs, data content type is of JSON. The body of the request should be in a string format i.e in double quotes but when I set it in a dictionary, I get the below result. Could anyone help me to set the NSString as string value in dictionary.
NSMutableDictionary *reqParams = [NSMutableDictionary new];
[reqParams setObject:#"Data.SourceStreamRequest"forKey:#"_type"];
NSMutableDictionary *reqParams1 = [NSMutableDictionary new];
[reqParams1 setObject:#"newmjpegdataSession"forKey:#"_type"];
NSLog(#"%#:%#",reqParams,reqParams1);
Output
{
"_type" = "Data.SourceStreamRequest";
}:{
"_type" = newmjpegdataSession;
}
Could anyone help me to figure out the reason why ,the dictionary values are shown with double quotes and without double quotes.
Thank you
Use NSJSONSerialization to serialize your dictionary. Try this:
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"_type", #"Data.SourceStreamRequest",
#"_type", #"newmjpegdataSession", nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"json:\n%#", resultAsString);
Output:
json: { "newmjpegdataSession" : "_type", "Data.SourceStreamRequest"
: "_type" }

iOS: JSON displays dictionary out of order. How to present a reordering?

Say we have the following dictionary:
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:currentItem], #"item number",
[NSNumber numberWithInt:([[item valueForKey:#"section"] intValue]+1)], #"section number",
currentDate, #"date of item",
[NSNumber numberWithDouble:timeDifference], #"time difference in millis",
nil];
Then I get the following output:
{
"time difference in millis" : 5.220093071460724,
"section number" : 1,
"date of item" : "28/04/2014 15:56:54,234",
"item number" : 3
}
I use the following code to convert the dictionary to JSON:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\\" withString:#""];
How can I manipulate the order in which the JSON string shows its keys. For example, I would like to have:
{
"item number" : 3,
"section number" : 1,
"date of item" : "28/04/2014 15:56:54,234",
"time difference in millis" : 5.220093071460724
}
or something else. The point is that I want control over this process. How do I get it? My first thought was writing a parser that shows the ordering in the way that I want.
Here are similar questions, but my emphasis is on manipulating the order instead of just recreating the order in which I put it from the dictionary.
JSON format: getting output in the correct order
Need JSON document that is generated to be in same order as objects inserted in NSMutableDictionary in iOS
NSDictionary is not ordered by definition.
Easiest will be to wrap everything into NSArray if you want to have same order.
To restate the question: how to take an inherently unordered input, produce a string who's specification is inherently unordered, but control the ordering of that string.
Reformatting the dictionary as an array would let you control input ordering, but produce a different output format.
The only reason I can imagine wanting to do this is if wish to use the JSON string not as JSON, but just as a string. The question can then be restated as just lexically reformatting the string.
How general purpose must it be? Can we assume that the JSON has simple, scalar values? Then...
- (NSString *)reorderJSON:(NSString *)json keys:(NSArray *)orderedKeys {
NSArray *splitJson = [json componentsSeparatedByString:#","];
NSMutableArray *splitResult = [NSMutableArray array];
for (NSString *key in orderedKeys) {
for (NSString *splitPair in splitJson) {
if ([self jsonPair:splitPair hasKey:key]) {
NSString *trimmedSplitPair = [splitPair stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"{}"]];
[splitResult addObject:trimmedSplitPair];
}
}
}
NSString *joinedResult = [splitResult componentsJoinedByString:#","];
return [NSString stringWithFormat:#"{%#\n}", joinedResult];
}
- (BOOL)jsonPair:(NSString *)pair hasKey:(NSString *)key {
// pair should begin with double quote delimited key
NSString *trimmedPair = [pair stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *splitPair = [trimmedPair componentsSeparatedByString:#"\""];
return [splitPair[1] isEqualToString:key];
}
Call it like this:
- (void)testJson {
NSDictionary *d = #{ #"time difference in millis": #5.220093071460724,
#"section number": #1,
#"date of item" : #"28/04/2014 15:56:54,234",
#"item number": #3};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSArray *orderedKeys = #[ #"item number", #"section number", #"date of item", #"time difference in millis"];
NSString *result = [self reorderJSON:jsonString keys:orderedKeys];
NSLog(#"%#", result);
}
You shouldn't want that. Dictionaries have no order and writing some code that uses the order will just lead to problems in the future.
That said, if you want to, you can write your own code to generate the JSON string from your (ordered) array of keys and dictionary of values.

Trouble iterating through Array

How's it going folks---I'm having trouble iterating through an array in xcode--hoping someone can point me in the right direction..here's my response json response
NSString *str=#"jsonUrlremoved";
NSURL *url=[NSURL URLWithString:str];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:&error];
{
   "item":{
      "1":{
         "title":"Item Title",
         "description":"long description",
         "date":" March 01, 2014"
      },
      "2":{
         "title":"Item Title",
         "description":"long description",
         "date":" March 01, 2014"
      },
      "3":{
         "title":"Item Title",
         "description":"long description",
         "date":" March 01, 2014"
      }
   }
}
I've tried converting to nsdictionary as well as nsobject and nsarray with no luck (cause I'm a noob)
NSDictionary *results = [response objectForKey:#"item"];
for (NSDictionary *result in results) {
NSString *image = [result objectForKey:#"image"];
NSString *desc = [result objectForKey:#"description"];
NSString *title = [result objectForKey:#"title"];
}
The app either crashes or returns null---any guidance is appreciated
For openers, your data doesn't have a value for the key #"image".
But beyond that, when you get the object for #"item", what it will return you is an array of three more dictionaries, with keys #"1", #"2", and #"3". Do a get on those keys, and you should then be able to get the subfields.
Do a 'po result' in the debugger when you breakpoint at the beginning of your 'for' loop. It will print out the type of the object you've got (whether it's an NSDictionary or NSArray) and change your code to agree to what's in your data structure.
Your JSON Object does not contain an array. So Iterating through it is out of question. You essentially have nested Dictionaries. If you need to do some Array stuff, I'd consider changing your JSON's Item object's value to an Array "[]" instead of a Dictionary "{}". That way, you don't even have to deal with indices in your JSON object. You get them for free.
The "Corrected" JSON object would look something like this:
{
"item":[
{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
},
{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
},
{
"title":"Item Title",
"description":"long description",
"date":" March 01, 2014"
}
]
}
One way of doing this if you dont't want to restructure your JSON can be as follows, it's just a way around not to be prescribed :P
NSDictionary *results = [response objectForKey:#"item"];
NSString *image = [[result objectForKey:#"1"]objectForKey:#"image"] ;
NSString *desc = [[result objectForKey:#"1"]objectForKey:#"description"];
NSString *title = [[result objectForKey:#"1"]objectForKey:#"title"];
and similarly for the rest of the objects

How to create an NSDictionary with multiple keys?

I am not sure if what I am going to ask is actually an NSDictionary with multiple keys but ok.
What I want to do is create an NSDictionary with keys and values for my data and then convert it to JSON format. The JSON format would look exactly like this :
{
"eventData": {
"eventDate": "Jun 13, 2012 12:00:00 AM",
"eventLocation": {
"latitude": 43.93838383,
"longitude": -3.46
},
"text": "hjhj",
"imageData": "raw data",
"imageFormat": "JPEG",
"expirationTime": 1339538400000
},
"type": "ELDIARIOMONTANES",
"title": "accIDENTE"
}
I ve only used NSDictionaries like this :
NSArray *keys = [NSArray arrayWithObjects:#"eventDate", #"eventLocation", #"latitude" nil];
NSArray *objects = [NSArray arrayWithObjects:#"object1", #"object2", #"object3", nil];
dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
But the above format is not all about key - value.
So my question is how would the NSDictionary be , to fit the JSON format??
Thanks for reading my post , and sorry if any confusion.
You can have a NSDictionary inside another NSDictonary:
NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:#"43.93838383",#"latitude",#"-3.46",#"latitude", nil];
NSMutableDictionary *eventData = [NSDictionary dictionaryWithObjectsAndKeys:eventLocation,#"eventLocation", nil];
[eventData setObject:#"Jun 13, 2012 12:00:00 AM" forKey:#"eventDate"];
[eventData setObject:#"hjhj" forKey:#"text"];
.
.
.
NSMutableDictionary *finalDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:eventData,#"eventData", nil];
[finalDictionary setObject:#"ELDIARIOMONTANES" forKey:#"type"];
[finalDictionary setObject:#"accIDENTE" forKey:#"title"];
Now with Objective-C literals there is a much better, easier, and cleaner way of accomplishing this. Here is your exact dictionary with this new syntax:
NSDictionary *dictionary = #{
#"eventData": #{
#"eventDate": #"Jun 13, 2012 12:00:00 AM",
#"eventLocation": #{
#"latitude": #43.93838383,
#"longitude": #-3.46
},
#"text": #"hjhj",
#"imageData": #"raw data",
#"imageFormat": #"JPEG",
#"expirationTime": #1339538400000
},
#"type": #"ELDIARIOMONTANES",
#"title": #"accIDENTE"
};
// Prints: "43.93838383"
NSLog(#"%#", dictionary[#"eventData"][#"eventLocation"][#"latitude"]);
How to Create NSArray and with Access for object using NSDictionary ?
... Create NSArray
NSArray *studentkeys = [NSArray arrayWithObjects:#"studentName", #"studentBirthDate", #"studentCity", #"studentMobile" nil];
NSArray *objects = [NSArray arrayWithObjects:#"Pravin", #"27/08/1990", #"Bhavnagar",#"7878007531", nil];
...to Access to NSArray Object Using NSDictionary
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
Here is the structure:
Your root object is NSMutableDictionary
eventData - key for object NSMutableDictionary with keys and objects:
->key eventDate object NSString
->key eventLocation object NSMutableDictionary with keys and objects:
----> key latitude object NSNumber
----> key longitude object NSNumber
-> key text object NSString
-> key imageData object NSString later converted to NSData
-> key imageFormat object NSString
-> key expirationTime object NSNumber
type key for object NSString
title key for object NSString
if you want multiple categories , you can follow this format
NSDictionary *jsonObject = #{
#"data1":#[
#{
#"title":#"A"
#"subData" : #[
#{
#"title":#"aa"
}]
}
]
};

Resources