How to parse json string into key value pairs? - ios

Unable to parse json string
I have got the following hard coded json. I tried converting it to dictionary and parse it but Im unable to do so.
NSString *hcResponse = #"{\"status\":1,\"value\":\"Successfully Login\"}";
How to parse such a json into key value pairs?

Finally, I've figured it by myself
//convert the string to nsdata
NSData *jsonData = [hcResponse dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
//convert the data to json dictionary
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];

Related

Invalid JSON String that extracted from HTML [duplicate]

After testing, I can only get [NSJSONSerialization isValidJSONObject:] to return a positive on JSON data that I have already parsed with [NSJSONSerialization JSONObjectWithData:options:error:].
According to the official documentation:
isValidJSONObject returns a Boolean value that indicates whether a given object can be
converted to JSON data.
However, despite the fact that the objects I am attempting to convert from JSON to a NSDictionary convert fine, isValidJSONObject returns NO.
Here is my code:
NSURL * url=[NSURL URLWithString:urlString];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error=[[NSError alloc] init];
NSMutableDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if([NSJSONSerialization isValidJSONObject:data]){
NSLog(#"data is JSON");
}else{
NSLog(#"data is not JSON");
}
if([NSJSONSerialization isValidJSONObject:dict]){
NSLog(#"dict is JSON");
}else{
NSLog(#"dict is not JSON");
}
NSLog(#"%#",dict);
My log contains the following:
data is not JSON
dict is JSON
and then the output of dict, which at this point is a huge NSMutableDictionary object. No errors are generated when running this code, but isValidJSONObject seems to be returning the wrong value when run on data.
How can I get isValidJSONObject to work as expected?
isValidJSONObject tests if a JSON object (a NSDictionary or NSArray) can be successfully
converted to JSON data.
It is not for testing if an NSData object contains valid JSON data. To test for valid
JSON data you just call
[NSJSONSerialization JSONObjectWithData:data ...]
and check if the return value is nil or not.

NSDictionary Sorting keys by default

I am working on API integration, From API I am getting the response in dictionary format, While I serialise that data, it is sorting automatically
Here is my code
id resposeJSon = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
While I try to print the same in NSString it works as the response is received
NSString *jsonString = [[NSString alloc] initWithData:adata encoding:NSUTF8StringEncoding];
I am expecting the serialised variable resposeJSon should be in the same format what I get from variable jsonString
Thanks in advance

Get string out of json object of only string

I have a Json string which is only a string in Json format, like below:
#""JSONContent""
Is there a way to get the content out from such JSON string? I've tried to use below code but it cannot be parsed to Dictionary
NSData *jsonData = [rawTime dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
First of all, if that is the reponse that you are getting, then probably it wont be recognized as JSON because JSON strings start with a '[' or '{' character. Hence, it wont be parsed. You have to make sure that the string you receive from the server is in proper JSON format or not. You can check the JSON string validation on this website : jsonlint.com
Now the code that you have tried will also not work because of the same reason, i.e improper JSON format. There can be many reasons so as to why JSON that is received is in a bad format. It also might be possible that your JSON might be embeeded in an XML string like as shown :
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">
[{"Title":"DemoTitle","CreationDate":"06/06/2014","Description":"DemoDescription"}]
</string>
This is just an example. So the conclusion here is : Make sure your JSON is in proper format, i.e starting with '[' or '{'.
As for the parsing code, this might help you :
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
This will fetch the JSON response from the service URL and then parse it using NSJSONSerialization and finally store the data in an array for further use.
Hope this helps.

Why is this JSON invalid using NSJSONSerialization?

I'm new to JSON and don't understand why this is failing. The JSON is valid according to on-line validation tools, but NSJSONSerilization says this the string is invalid. Why is it invalid?
NSString* JSON = #"{\"Questionnaire\":{\"questionnaireid\":1,\"modifiedDate\":\"2012-12-28 15:27:00\"}}";
if (![NSJSONSerialization isValidJSONObject:JSON]) {
return nil;
}
NSError *jsonParsingError = nil;
NSDictionary* data = [NSJSONSerialization dataWithJSONObject:JSON options:NSJSONReadingMutableContainers error:&jsonParsingError];
why you did serialization when you already created JSON yourself ?
What you should do:
NSData *jsonPayload = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonPayload
options:kNilOptions error:&error];
Because a JSON Object must be of type NSArray or a NSDictionary while you are passing a NSString.
From the docs:
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
UPDATE
You probably want to do this:
NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];

iOS JSON NSString Parse

I have a JSON string as an NSString object in iOS. I want to parse this and pull out the given parameters in the JSON string. Is there a efficient way to parse this or is the only way to search for substrings etc.?
The way to do it with iOS 5 is to use the NSJSONSerialization class. You will want to first convert your string to an NSData object, and call the class method JSONObjectWithData
NSData *jsonData = [myJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
Note that JSONObjectWithData will return either an NSDictionary or an NSArray, depending whether your JSON string represents an a dictionary or an array.
A good framework for converting JSON strings to Objective-C objects (NSArray and NSDictionary) is SBJson (Github).
Usage:
NSDictionary *dict = [myJsonString JSONValue];

Resources