NSDictionary format - ios

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

Related

Setting data in correct JSON format using Array and Dictionary

Below is the model for which I have to set the data. I am using array and dictionary to achieve this, Here is the code which I tried. But its giving me the output which is invalid JSON.
One more thing I want to ask is why the log of an array starts and ends with small braces?
Any help would be much appreciated.
Code:
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
parameterName,#"parameterName",
parameterType, #"parameterType",
[NSNumber numberWithBool:parameterSorting],#"parameterSorting",[NSNumber numberWithBool:parameterSorting],
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:paramData];`
Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":"(
{
parameterName = anandShankar;
parameterOrdering = 1;
parameterSorting = 1;
parameterType = Text;
}
)","catalogMode":"xxxxxx"}}
Desired Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":[{
"parameterName" : "anandShankar",
"parameterOrdering" : 1,
"parameterSorting" : 1,
"parameterType" : "Text"
}],"catalogMode":"xxxxxx"}}
There is nothing wrong in it. in console or log round braces () indicates array. if it is showing round braces then it is array. you will never het [] square braces in console or log.
Update :
NSData *data = [NSJSONSerialization dataWithJSONObject:paramData options:kNilOptions error:nil];
and then send this data to server. it will in your desired json fromat
hope this will help :)
Try this code :
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
#"Object1",#"parameterName",
#"Object2", #"parameterType",
#'Object3',#"parameterSorting",#"Object4",
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
Add this lines :
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:paramData options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString); // it will print valid json
JSON
{
"rqBody":{
"catalogName":"",
"parameter":[
{
"parameterOrdering":"Object4",
"parameterName":"Object1",
"parameterType":"Object2",
"parameterSorting":51
}
],
"userId":"",
"catalogMode":""
}
}

How assign value to a JSON string?

I get this JSON object from my web service
0: {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}
When I try to assign a value, for example, to Username JSON string, I get a semantic error:
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
for (NSDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString ;
I know how get the JSON object with NSJSONSerialization class, but my target is how assign the value #"" to the JSON object.
So how can I assign the value #"" to the Username JSON string?
While you are trying to fetched dictionary from array. it is not mutable dictionary so you need to created NSMutableDictionary while fetching data from Array. following code will help you to change username.
for (NSMutableDictionary *dictionary in array)
{
NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[dictTemp setObject:usernameString forKey#"Username"];
[_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}
Well your assignment operation is written wrong, it should be indeed like this:
If you need to get value from dictionary
usernameString = [dictionary objectForKey:#"Username"];
If you want to set a value to your dictionary, first of all your dictionary should be NSMutableDictionary
[dictionary setObject:usernameString forKey:#"Username"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if(!error && [obj isKindOfClass:[NSArray class]]){
NSArray *array = (NSArray *)obj;
Booking *booking = nil;
for (NSMutableDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString;
Yes, is a compiler error
You need to have a mutabledictionary inorder to change the value. Try this
for (NSDictionary *dictionary in array) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
NSString *usernameString = #"";
[mutableDictionary setValue:#"" forKey:usernameString];
}
Even the answers are correct, I want to add that you do not have to do this your own. NSJSONSerialization already has a solution for that. Simply pass as options one of these:
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
when reading the JSON.

Incorrectly parse json into NSDictionary

I am trying store text fields data into a NSDictionary from json. I have used SBJson for this.
{
"fields":[
{
"textFields":[
{
"text":"Congratulations",
"textSize":"12"
},
{
"text":"Best Wishes",
"textSize":"15"
},
{
"text":"Test text",
"textSize":"10"
}
]
},
{
"imageFields":[
{
"image":"test1.jpg",
"width":"200",
"height":"100"
},
{
"image":"test2.jpg",
"width":"200",
"height":"100"
}
]
}
]
}
My code:
-(void)readJson{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
But its output as follows.
Dictionary (
(
{
text = Congratulations;
textSize = 12;
},
{
text = "Best Wishes";
textSize = 15;
},
{
text = "Test text";
textSize = 10;
}
),
"<null>"
)
It seems like there are two items in dictionary and one is null. I wanted to put three textfield items into the array. How can i solve this.
Don't use SBJSON. Use NSJSONSerialization.
Don't use valueForKey:, use objectForKey:.
You are mixing up dictionaries and arrays. Don't do that. Use NSArray for arrays.
I am revising your code for better understanding
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
More appropriate way is
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fieldsArr =[jsonDict objectForKey:#"fields"];
for(int i=0;i<[fieldArr count];i++)
{
NSArray *textFieldArr = [fieldArr objectAtIndex: i];
for(int j=0;j<[textFieldArr count];j++)
{
NSDictionary *dicTextField = [textFieldArr objectAtIndex: j];
NSString *text = [dicTextField objectForKey: #"text"];
NSString *textSize = [dicTextField objectForKey: #"textSize"];
}
}
}
For quick help
treat { as dictionary and [ as array.
Hope, i am helpful to you.
As your json format, [jsonDict valueForKey:#"fields"] will return an array not dictionary so your code must be
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fields = [jsonDict objectForKey:#"fields"];
NSDictionary *fieldsDict = fields[0];
NSArray *textFieldsDict = [fieldsDict objectForKey:#"textFields"];
I have corrected the json format and used NSJSONSerialization,
{"fields":
{"textFields":
[ {"text":"Congratulations", "textSize":"12"},
{"text":"Best Wishes", "textSize":"15"},
{"text":"Test text", "textSize":"10"}
],
"imageFields":
[ {"image":"test1.jpg","width":"200", "height":"100"},
{"image":"test2.jpg", "width":"200", "height":"100"}
]
}
}
-(void)readJson
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSDictionary *fields = [jsonDict objectForKey:#"fields"];
NSArray *textArray=[fields objectForKey:#"textFields"] ;
NSLog(#"--- %#",textArray );
}

After convert JSON array to NSDictionary, what should I do?

I need to parse a JSON array in the following format:
[
{
name: "10-701 machine learning",
_id: "52537480b97d2d9117000001",
__v: 0,
ctime: "2013-10-08T02:57:04.977Z"
},
{
name: "15-213 computer systems",
_id: "525616b7807f01fa17000001",
__v: 0,
ctime: "2013-10-10T02:53:43.776Z"
}
]
So after getting the NSData, I transfer it to a NSDictionary:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#", dict);
But viewing from the console, I think the dictionary is actually like this:
(
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
ctime = "2013-10-08T02:57:04.977Z";
name = "10-701 machine learning";
},
{
"__v" = 0;
"_id" = 525616b7807f01fa17000001;
ctime = "2013-10-10T02:53:43.776Z";
name = "15-213 computer systems";
}
)
What do those parenthesis in the outside mean? How should I further transfer this NSDictionary to an NSArray or an NSMutableArray of some Course objects (what I defined myself, try to represent each element of the JSON array)?
Use this code,
NSArray *array = [NSJSONSerialization JSONObjectWithData: responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dict = [array objectAtIndex:0];
Then you can retrieve the values by following code,
NSString *v = [dict objectForKey:#"__v"];
NSString *id = [dict objectForKey:#"_id"];
NSString *ctime = [dict objectForKey:#"ctime"];
NSString *name = [dict objectForKey:#"name"];
The parenthesis are just the result of NSDictionary output format not being exactly the same thing as how JSON is formatted. Your code still successfully converted the JSON into a NSDictionary object.
I think what you really want, though, is an array of dictionaries. Something like this:
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *firstObject = [json objectAtIndex:0];
After this, firstObject would contain:
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
"ctime" = "2013-10-08T02:57:04.977Z";
"name" = "10-701 machine learning";
}
And you can retrieve the information with objectForKey:
NSString *time = [firstObject objectForKey:#"ctime"];
// time = "2013-10-08T02:57:04.977Z"
Hope that helps.

Cant access serialized JSON data (NSJSONSerialization)

I get this JSON from a web service:
{
"Respons": [{
"status": "101",
"uid": "0"
}]
}
I have tried to access the data with the following:
NSError* error;
//Response is a NSArray declared in header file.
self.response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *test = [[self.response objectAtIndex:0] objectForKey:#"status"]; //[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
NSString *test = [[self.response objectForKey:#"status"] objectAtIndex:0]; //(null)
But none of them work, if i NSLog the NSArray holding the serialized data, this i what i get:
{
Respons = (
{
status = 105;
uid = 0;
}
);
}
How do i access the data?
Your JSON represents a dictionary, for whom the value associated with the Respons key is an array. And that array has a single object, itself a dictionary. And that dictionary has two keys, status and uid.
So, for example, if you wanted to extract the status, I believe you need:
NSArray *array = [self.response objectForKey:#"Respons"];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *status = [dictionary objectForKey:#"status"];
Or, in latest versions of the compiler:
NSArray *array = self.response[#"Respons"];
NSDictionary *dictionary = array[0];
NSString *status = dictionary[#"status"];
Or, more concisely:
NSString *status = self.response[#"Respons"][0][#"status"];
Your top level object isn't an array, it's a dictionary. You can easily bypass this and add the contents of that key to your array.
self.response = [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error] objectForKey:#"Respons"];

Resources