Json Response parsing - ios

I got json reponse in the following way...i have tried to parse in many ways all went ruin.
dic:
(
{
events = {
id = 1;
name = "Event One";
};
},
{
events = {
id = 2;
name = "Test 2";
};
},
{
events = {
id = 12;
name = "vivek 11";
};
},
)
NSDictionary *jsonDictionaryResponse = [response JSONValue];
NSString *name=[[[jsonDictionaryResponse objectForKey:#"events"]objectAtIndex:0]valueForKey:#"name"];
json response:
Login response :[{"events":{"id":"1","name":" Event
One"}},{"events":{"id":"2","name":"Test
2"}},{"events":{"id":"12","name":"vivek
11"}},{"events":{"id":"13","name":"Baby's Day
out"}},{"events":{"id":"15","name":"Childrens
Day"}},{"events":{"id":"16","name":"event
two"}},{"events":{"id":"17","name":"Test
Creattion"}},{"events":{"id":"29","name":"Susan
Test"}},{"events":{"id":"30","name":"Summer
Holidays"}},{"events":{"id":"38","name":"Event
7"}},{"events":{"id":"69","name":"vivek event for
tests"}},{"events":{"id":"102","name":"chinees food mela"}}]

first transform your response string to NSData. then try this:
NSError *error;
NSArray *jSONArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
for (NSDictionary *dict in jSONArray) {
NSDictionary *event = [dict objectForKey=#"events"];
NSString *name = [event objectForKey:#"name"];
....
}

The easiest way to understand a JSON object in Objective-C is to understand how it breaks things up into Arrays and Dictionaries. Every time you see a "[" think Array. Every time you see a "{" think Dictionary.
An Array can have Dictionary or other Array objects as part of the collection and a Dictionary can have Array or more Dictionary objects which can contain more Arrays or Dictionaries.
If you remember that "[ ]" means Array and "{ }" means Dictionary, you will know JSON in Objective-C.

Check that result coming as JSON. it is not aDictionary check it
here
PLease find the code here
NSArray *jsonArrayResponse = [response JSONValue];
NSDictionary *firstDic = [jsonArrayResponse objectAtIndex:0];
NSDictionary *secondDic = [firstDic objectForKey:#"events"];
NSLog(#"The values in the events dictioanry is %# ",[secondDic allValues]);
NSString *stringNAme = [secondDic objectForKey:#"id"];

Related

How To Get Particular Values From Json Response Using Objective C?

I am trying to get response of first key value without mentioning key name of "A" using objective C. I cant get exactly, please help me to get from below response.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = [JSON[#"response"]firstObject];
response = {
A = {
company = (
{
no = "115";
student = "Mich";
school = (
{
grade = A;
}
);
test = "<null>";
office = tx;
}
);
};
}
There are a few ways to do this, depending on your exact requirements. If you just need to access the value of each key in JSON[#"response"], you can enumerate the JSON dictionary:
[JSON enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSDictionary *dict = (NSDictionary *)obj;
...
if (shouldStop) { // whatever condition you want, if any
*stop = YES;
}
}];
If you want some kind of ordering, you need to use [JSON allKeys]:
NSArray *keys = [[JSON allKeys] sortedArrayUsing...]; // Use whichever sort method you like
for (NSString *key in keys) {
NSDictionary *dict = JSON[key];
...
}
If all you want are the values, you can use [JSON allValues]. Sort if desired.

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.

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

Understand and use this JSON data in iOS

I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];

Resources