Parse JSON data is returning null value - ios

I am getting JSON data with below code as string. But really very confusing to solve this
NSString *htmlSTR = [[NSString alloc] initWithData:self.receivedData
encoding:NSUTF8StringEncoding];
NSLog(#"userdetail :%#" , htmlSTR);
But i need to parse the Id only.
I parsed with the code of
NSDictionary *JsonDict = [NSJSONSerialization JSONObjectWithData:self.receivedData options: NSJSONReadingMutableContainers error: &e];
NSLog(#"json %#",jsonArr1);
NSString *string=[JsonDict valueForKey:#"Id"];
But its returning null value for string, even for integer it is returning numeric zero
userdetail : {"Country":"Afghanistan","CreatedBy":"raje#gmail.com","FirstName":"rajeev","Gender":"M","LastName":"leader","ModifiedBy":"raje#gmail.com","Password":"asdf","emails":"raje#gmail.com","id":32}
This is the first time am trying this thing, help me to solve this.Sorry for bad formatting.

only change this line .
NSString *string=[JsonDict valueForKey:#"Id"];
TO
NSString *string=[JsonDict valueForKey:#"id"];
Hope this works for you.

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 to parse JSON data from textual file in Objective-C

I know, JSON parsing questions are asked over and over again, but still I can't find any answer to this one.
I've been trying to read and parse a textual JSON file using NSJSONSerialization to no avail.
I've tried using the same JSON data from a NSString and it did work.
Here's the code:
NSError *error;
NSString *jsonString1 = [NSString stringWithContentsOfFile:jsonFilePath
encoding:NSUTF8StringEncoding
error:&error];
NSData *jsonData1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:jsonData1
options:0
error:&error];
NSString *jsonString2 = #"{\"key\":\"value\"}";
NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject2 = [NSJSONSerialization JSONObjectWithData:jsonData2
options:0
error:&error];
- The text file contains one line: {"key":"value"}
- jsonString1 = #"{"key":"value"}"
- jsonString2 = #"{\"key\":\"value\"}"
- jsonData1 is 23 bytes in size
- jsonData2 is 15 bytes in size
- jsonObject1 is nil and I get error code 3840
- jsonObject2 is a valid dictionary
Seems like the problem is with reading the file, since the NSStrings and NSDatas differ, but what am I doing wrong here and how can I fix it?
Most likely you file contains some unprintable characters (e.g. \0) that trigger the failure. Printing the error message will tell you at what position the first invalid characters occurs.
For example, try printing "{\"key\":\u{0000}\"value\"}" and you'll seem to get a valid JSON, however decoding it fails.
I always do a check on the return value when doing anything with NSUTF8StringEncoding and if nil, then try NSASCIIStringEncoding:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (jsonString == nil) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
}
return jsonString;

how to remove the \ character

I have a string with the following information:
\"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]\"
and I need to delete the character \ I'm trying to remove as follows, but the character is using the system and leaves close the line of code
NSString *filtered = [[[restConnection stringData] componentsSeparatedByString:#"\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);
the error is
Expected ']' in this part : componentsSeparatedByString:#"\"]
Its looks like JSON data, instead interfering into JSON, just convert JSON string to NSData and then into NSDictionary or NSArray
NSString *jsonString = #"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *array = [NSArray arrayWithArray:json];
Now if you do following NSLog statement
NSLog(#"%#",[[json firstObject] objectForKey:#"CodRTA"]);
Result would be another NSDictionary.
{
CodRTA = 1;
MenssRTA = messaje error;
Resp = "";
}
Btw, I formatted your JSON response, its look like this,
Someting like that
string = [string stringByReplacingOccurrencesOfString:#"\\" withString:#""];
use this code
NSString *str=#"[{\"CodRTA\":\"1\",\"MenssRTA\":\"messaje error\",\"Resp\":\"\"}]";
NSString *filtered = [[str componentsSeparatedByString:#"\\"] componentsJoinedByString:#""];
NSLog(#"filtrado: %#", filtered);

NSData to NSString with JSON response

NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(#"%#", [jsonDict objectForKey:#"result"]);
then you will get the expected output
說
I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…
NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …];
…and you should get the following dictionary back: #{#"result":#"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.
BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.

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