How to create an NSDictionary with multiple keys? - ios

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

Related

How to IntersectSet of two NSDictionary or NSMutableDictionary with values?

Want to merge two NSDictionary or NSMutableDictionary only with dict1 values. like [NSMutableDictionary addEntriesFromDictionary:] and intersectSet (from NSMutableSet).
Dict 1 = #{#”One”: #””, #”Two”: #”"}
Dict 2 = #{#”One”: #”1”, #”Two”: 2, #”Three”: #”3"}
My expect output after merge = #{#”One”: #”1”, #”Two”: #”2"}
UPDATE
I am already tried with [Dict1 addEntriesFromDictionary:Dict2] this one give answer #{#”One”: #”1”, #”Two”: 2, #”Three”: #”3"}
Also I am tried with NSMutableSet
NSMutableSet *keysInA = [NSMutableSet setWithArray:tempDict.allKeys];
NSSet *keysInB = [NSSet setWithArray:tempDict1.allKeys];
[keysInA intersectSet:keysInB];
NSLog(#"keys in A that are not in B: %#", keysInA);
This one give output One, Two, Three.
So [NSMutableSet setWithArray:] and [NSMutableDictionary addEntriesFromDictionary:] won't give what I expected.
If above code have anything work let clear me. Thanks.
NSDictionary *dict1 = #{#"One": #"", #"Two": #"6"};
NSDictionary *dict2 = #{#"One": #"1", #"Two": #"2", #"Three": #"3"};
NSDictionary * dict = [dict2 dictionaryWithValuesForKeys:[dict1 allKeys]];
NSLog(#"dict %#",dict);
// Log value
dict {
One = 1;
Two = 2;
}
Here what I expected.
try this...
//Assuming both dictionaries have same kind of keys
NSMutableDictionary *dict1 = #{#"One" : #"", #"Two": #"", #"Three" : #""}.mutableCopy;
NSDictionary *dict2 = #{#"One" : #"1", #"Two": #"2", #"Three" : #"3",#"Four":#"4"};
for (NSString *key in dict1.allKeys)
{
if (dict2[key])
{
dict1[key] = dict2[key];
}
}
NSLog(#"Updated dict %#",dict1);

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

add multiple key and value in Dictionary

I want to add multiple value in NSDictionary. They make me trouble.
I am newer in Swift.
m=NSDictionary(objectsAndKeys:[self.getStringAt(selectStmt, column: 0)],"first",[self.getStringAt(selectStmt, column: 1)],"second",nil)
You can do it like this.
let interestingNumbers = [
"Prime" : [2,3,5,7,11,13],
"Fibonacci" : [1,1,2,3,5,8],
"Square" : [1,4,9,16,25]
]
Hope this helps.
/* Collection Types: Dictionary */
var dic1 = ["math":89, "chemistry":90, "physics":79]
// Modifying
dic1["math"]
dic1["math"] = 70 // returns new value
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"];

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 generate JSON programmatically using JSON framework for iPhone

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

Resources