Understand and use this JSON data in iOS - 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"];

Related

NSTaggedPointerString objectForKey in objective-c

when I try to fetch the result from the JSON result. It throws the following exception.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSTaggedPointerString objectForKey:]: unrecognized selector sent to instance 0xa006449656c6f526'
My code.
NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
mutableData options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *firstname = [dataDict objectForKey:#"FirstName"];
}
The above code throws an NSException.
My JSON response looks like this.
{
"IsExternal": 0,
"LoginId": 4,
"EmployeeId": 223,
"FirstName": "GharValueCA",
"RoleId": 4,
"LastName": null,
"Mobile": null,
"AgencyId": 100,
"BranchId": 74
}
Any help will be appreciated.
According to the definition of JSON, each JSON contains one object (which can be a collection type that contains other objects). In your case, your text starts with "{", so that's a dictionary. A single dictionary.
So NSJSONSerialization, when it reads that file, gives you back an NSDictionary containing values under keys like IsExternal, FirstName etc.
However, your code uses for( ... in ... ) on that dictionary (which, according to NSDictionary documentation, will iterate over the keys in the dictionary, which are strings), but then you treat those strings as if they were dictionaries again.
So instead of looping over the dictionary, you should just use the dictionary in jsonObjects directly, by calling something like -objectForKey: on it.
There is a misunderstanding:
jsonObjects is already the dictionary, assign the deserialized object immediately to dataDict.
NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:mutableData
options:0
error:nil];
// mutableContainers in not needed to read the JSON
The enumerated objects are strings, numbers or <null>. You called objectForKey: on a string which caused the error.
Get the name directly (no loop)
NSString *firstname = dataDict[#"FirstName"];
or you can enumerate the dictionary
for (NSString *key in dataDict) {
NSLog(#"key:%# - value:%#", key, dict[key]);
}
You should call
[jsonObjects objectForKey:#"FirstName"];
to get the FirstName value.
Below lines of code returns you (probably) a NSDictionary, so this is the container that stores all of your json values.
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
mutableData options:NSJSONReadingMutableContainers error:nil];
Try this code:
if ([jsonObjects isKindOfClass:[NSDictionary class]]) {
NSString *firstname = [jsonObjects objectForKey:#"FirstName"];
}
as your 'jsonObjects' is of generic type 'id' so just check that whether it is of NSDictionary type and then in if-block you can directly access it by objectForKey:
try this code, hope it help,
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
mutableData options:NSJSONReadingMutableContainers error:nil];
if([jsonObjects respondsToSelector:#selector(objectForKey:)]){
NSString *firstname = [jsonObjects objectForKey:#"FirstName"];
}

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.

Converting JSON ARRAY into NSNumber Arrays

I've retrieved data from a JSON web service and saved it into the following array
_soldamount =
(
0,
0,
0,
0,
"62.69",
"48.3",
81,
"59.83",
"162.57",
0,
"40.67",
)
I believe this array is saved as a string. how can I convert this array into an array of NSnumbers? Thanks for the help!
NSArray *_soldamount = #[ #0, #0, #0, #0, #"62.69", #"48.3", #81, #"59.83", #"162.57", #0, #"40.67"];
NSArray *numbers = [_soldamount valueForKey:#"doubleValue"];
creates an array of NSNumbers. The original array can contain NSNumber
or NSString objects.
You can do it using the following code:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&e];
What is stored in the json variable will depend on the JSON data. It is most commonly either an NSDictionary or NSArray, and it looks like yours would be an NSArray probably.
If these values are intended to be stored as numbers, your web service should be returning them as such. In other words, a value with quotes (") around it is a string regardless of whether or not the string is numerical.
If you do not have control of the web service and still wish to store these values as NSNumbers, you can use [NSNumber numberWithFloat:[string floatValue]] or you may wish to use [string doubleValue] if the strings may contain large values or high precision floating point values.
See Gavin's answer on how to use the NSJSONSerialization class if you aren't using it already.
NSError *error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray *soldAmount = [json objectForKey:#"amount"]; // Your array of strings.
// Convert string array to number array
NSMutableArray *numberArray = [NSMutableArray array];
[soldAmount enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[numberArray addObject:[NSNumber numberWithFloat:[(NSString *)obj floatValue]]];
}];
use [NSnumber numberWithInteger:[string integerValue]]

Json Response parsing

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

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