JSON Parsing, Objective c - objective-c

callback({"success":"TRUE","total_records":1,"data":[{"status_value":"1","status_text":"Login Successful","user_id":"5","u_name":"Tushar Verma"}]})
I have a service which gives the above result, so how can i get the data value using json parsing in objective c.
Thanks for the help in advance.

The NSJSONSerialization is available to iOS from 5.0 onwards.
It provides convenient methods to convert the data representation of JSON response from a server to the appropriate NSArray or NSDictionary methods.
It's harder to give a more detailed answer as you've asked such a general question.

use this simple code :-
NSString *str = #"{\"success\":\"TRUE\",\"total_records\":1,\"data\":[{\"status_value\":\"1\",\"status_text\":\"Login Successful\",\"user_id\":\"5\",\"u_name\":\"Tushar Verma\"}]}";
NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSArray *arr =[dic objectForKey:#"data"];
NSLog(#"%#", arr);

Related

Incorrect result from NSJSON Serialization

I have got a very strange issue when I trying to deserialize my json string, the code is this:
NSString *testString = #"{\"cash\": 99946.222300000000}";
// NSString *testString = #"{\"cash\": \"99946.222300000000\"}"; //It's correct if I use this one
NSData *jsonData = [testString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Convertion result is %#",error?#"false":#"true");
NSLog(#"Result data is\n %#",jsonObject);
And the result is :
2017-08-30 18:04:36.430 DAE[45557:2989692] Conversion result is true
2017-08-30 18:04:36.430 DAE[45557:2989692] Result data is
{
cash = "99946.22229999999";
}
So can anybody tell me if I did anything wrong? and how to solve it?
Really appreciate for any help.
First of all, it’s not wrong, it’s correct.
So, why you got the incorrect result?
First, The json value will be converted to a NSNumber object by NSJSONSerialization;
Then, the -description method of NSDictionary generate the result by stringValue method.
You should resolve the json value by this way to get the correct string:
[NSString stringWithFormat:%lf, [jValue doubleValue]]
But you should pay attention to the length of the value, the max length of double is 16, so if you get a number over than it, you will never get the correct result.
Tell your backend guy that they should convert all the numbers to string before they give them out, because it’s really hard to resolve them correctly if it’s big enough.
use it as Your commented string
NSString *testString = #"{\"cash\": \"99946.222300000000\"}";
NSData *jsonData = [testString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Convertion result is %#",error?#"false":#"true");
NSLog(#"Result data is\n %#",jsonObject);

Best way to parse a JSONP response

I am calling an API, which should return a JSON file. Here is the API link: http://sg.media-imdb.com/suggests/h/hello.json
The problem is: this JSON file has something wrapping the JSON response
imdb$hello(JSON)
So the best approch that I can see is to use a regex expression to extract only what I need. Something like: ~/\((.*)\)/.
However I would like to use the new JSON iOS5 API, which (as far as i know) only accepts NSData as input. So, I don't want to convert my response from NSData to NSString, parse that using regex, and put that in another NSData object.
Can anyone see a better/cleaner solution for that JSON parsing?
What you have isn't JSON, but JSONP. If you're not in JavaScript, I believe the correct way to handle is just as you say, preprocess and then parse.
NSError *jsonError = nil;
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSRange range = [jsonString rangeOfString:#"("];
range.location++;
range.length = [jsonString length] - range.location - 1;
jsonString = [jsonString substringWithRange:range ];
NSJSONSerialization *jsonResponse =
[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
Why don't you just do something like this before parsing the JSON?
response = [response stringByReplacingOccurrencesOfString:#"imdb$hello" withString:#""];
How regular is this string. It will always be there?
// Remove #"imdb$hello(" and #")" that wraps the response string.
NSRange JSONRange = NSMakeRange(11, [responseString length] - 12);
NSString *JSONString = [responseString substringWithRange:JSONRange];
// Now you can parse as normal…
You will need to craft the method of peeling away the wrapper with your own level of certainty.

How to convert a JSON array into an NSArray

I've been having trouble finding out how to convert a JSON array into an NSArray.
I have a php script that creates an array that is converted into JSON which is then sent and stored into an NSString that looks like:
[1,2,3,4]
My problem is that I need to make that into an NSArray of ints. How would one do that?
Thanks!
You should look at the documentation of the NSJSONSerialization class.
You can hand it the NSData received from a remote call that is a string in JSON format and receive the array or dictionary it contains.
NSObject *o =[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
// other useful "options":
// 0
// NSJSONReadingMutableLeaves
// NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers
you should then check that o is of the type you expect for sanity purposes
If I wanted to quickly break that into an array I would do it like this:
NSString * jstring = #"[1,2,3,4]"; //your json string
jstring = [jstring stringByReplacingOccurrencesOfString:#"[" withString:#""];
jstring = [jstring stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray * intArray = [string componentsSeparatedByString:#","];
//you could create your int from the array like this
int x = [[intArray objectAtIndex:0]intValue];
Import the SBJson in your project (drag and drop it)
#import "SBJson.h"
Then where you receive the JSON response from the php file
NSArray *array = [responseString JSONValue];

Convert NSArray of bytes to NSData

I'm trying to download a file in Objective-C from a REST service but having some issues. Right now, the service returns a byte[] in JSON. I was able to get the array by using the json-framework.
NSURL *url = [NSURL URLWithString:#"http://192.168.10.215:8888/Service/RO/GetAllTheBytes/test.txt"];
NSString *str = [[NSString alloc] initWithContentsOfURL:url];
NSDictionary *jsonDic = [str JSONValue];
NSArray *fileContents = [jsonDic objectForKey:#"fileContents"];
Now I want to use this array of bytes to create a file, but I'm having trouble creating the file. Should I convert the NSArray to NSData, and how?
Change your service to return a Base64 string. There are a bunch of Objective-C Base64 decoders out there, some of which are half-decent.
A NSArray of NSNumbers is really really really stupid, with a minimum space overhead of about 300% (although not quite as bad as JRA-11693).

Objective-C: How to put boolean values in JSON dictionary?

I could not find out how to insert a boolean value (to appear as key:true in the JSON string) in my NSDictionary:
NSMutableDictionary* jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue: YES forKey: #"key"];
The code above does not run (obviously because YES is not an object).
How can I accomplish this?
You insert booleans into a dictionary using NSNumber. In this case, you can use the literal expression #YES directly, together with a dictionary literal, to make this a one-liner:
NSDictionary *jsonDict = #{#"key" : #YES};
To encode it to JSON, use +[NSJSONSerialization dataWithJSONObject:options:error]:
NSError *serializationError;
NSData *jsonData = [NSJSONSerialization
dataWithJSONObject:jsonDict
options:0 error:&serializationError];
if (!jsonData) {
NSLog(#"%s: error serializing to JSON: object %# - error %#",
__func__, jsonDict, serializationError];
}
+[NSNumber numberWithBool:] is the typical way to add a boolean to a NSDictionary.
With Objective-C literals, [NSNumber numberWithBool:YES] can be represented with just #YES,
You can create your dictionary like so:
NSDictionary *jsonDict = #{#"key":#YES};