Effectively parse single-element JSON in objective-c - ios

This is the situation: in Objective-C, I'm fetching JSON data from my server. I know for sure (and it won't change) that my JSON data only contains one JSON element named token that is a string. It will look like this :
{
"token": "ertvgbyhnujk45678CVBNkjuhgfvgb"
}
What's the way to just get the token string value? It's probably very easy but I'm totally new to Objective-C.

Use the following:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
Then get the token by using: dictionary[#"token"].
The error parameter in the method above can be nil because you said you're sure that it won't change and it'll always be JSON.

NSString *token = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil][#"token"];

Related

NSJSONSerialization isValidJSONObject returns false for received data from Venue search endpoint

Xcode 8.1 Deployment target iOS 9.0
I'm getting an array of compact venue objects as expected from Foursquare Venue Search endpoint in...
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
When I check the data object using...
if ([NSJSONSerialization isValidJSONObject:data])
i get a false.
Can someone tell me what is wrong over here?
Edit:
Here is the complete if block (after adding typecast to data in if block)...
id foundationObject;
NSLog(#"data:- %#",data);
if ([NSJSONSerialization isValidJSONObject:(id)data])
{
foundationObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"venues foundation object:- %#",foundationObject);
}
Earlier the code didn't have the if block. just...
id foundationObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
The change was made when I realized (using breakpoint just after the above statement) that foundationObject was nil even though data wasn't.
Note: this worked fine earlier when I shipped my app for iOS 9.x in march. Could the version of the Venue Endpoint being called be making a difference?
What you're testing here is for NSData. The input for isValidJSONObject is id not NSData
+ (BOOL)isValidJSONObject:(id)obj;
It returns YES if obj can be converted to JSON data (NSData), otherwise NO.
Also, according to documentation,
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.
Calling isValidJSONObject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.
For converting NSData to JSONObject, you can use the following code
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (!error) {
// successfully done.
}else {
NSLog(#"error: %#", error.localizedDescription)
}
Please note that to find out what's wrong with jsonData(NSData) you're receiving from the server, you have to pass NSError object into the method as shown in the above code. If conversion of NSData into jsonObject fails, you can find out why according to that.
Please look in to this link for more information on using NSError objects in Objective-C
You are using a wrong method here isValidJSONObject will tell you whether JSON object (id) will be converted to JSON data or not.
As per the doc
Returns a Boolean value that indicates whether a given object can be
converted to JSON data.
YES if obj can be converted to JSON data, otherwise NO.
If you want to check Data then you should use JSONObjectWithData:options:error: and check if it is nil or not.
Edit
You need to first convert your Data to NSDictionary or NSArray like this
NSMutableDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
then check if dict is a valid son or not like this
if([NSJSONSerialization isValidJSONObject:dict]){
NSLog(#"dict is a valid JSON");
}else{
NSLog(#"dict is not valid JSON");
}

Getting one value from JSON API in Objective-C

I'm trying to get one value from JSON. JSON is located in NSString and it looks like this:
{"coord":{"lon":-122.38,"lat":37.57},"weather":[{"id":300,"main":"Drizzle","description":"Lekka mżawka","icon":"09d"}],"base":"stations","main":{"temp":304.74,"pressure":1017,"humidity":35,"temp_min":300.15,"temp_max":307.59},"visibility":16093,"wind":{"speed":6.7,"deg":250},"clouds":{"all":75},"dt":1437346641,"sys":{"type":1,"id":478,"message":0.0615,"country":"US","sunrise":1437311022,"sunset":1437362859},"id":5357155,"name":"Hillsborough","cod":200}
I'm interested in getting "temp". How should I do that?
Assuming your JSON string was stored as a NSString named JSONString:
NSError *error;
NSDictionary *keys = [NSJSONSerialization JSONObjectWithData:[JSONString dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
NSLog(#"temp = %#", keys[#"main"][#"temp"]); // temp = 304.74
To get the main sub item in weather, which is an array with multiple items, you should point out its index to tell the selector which object in the array is the one you are looking for. In this case, it's 0:
NSLog(#"weather = %#", keys[#"weather"][0][#"main"]); // weather = Drizzle

IOS Dev Fetching JSON Data

I am a novice at IOS dev and i really need some help.
I want to parse (which is working) and fetch some JSON Data.
i used this tutorial for the http request and json parsing
http://www.mysamplecode.com/2013/04/ios-http-request-and-json-parsing.html
everything works fine with a 1 dimensional dictionary
but I need to be able to fetch the following JSON Data
[{"defaultGateway": "10.10.10.254", "hostname": "On", "connected": "true", "subnetMask": "255.255.255.255", "iPAddress": "10.10.10.10", "dhcpEnabled": "true"},
{"defaultGateway": "10.10.10.254", "hostname": "On", "connected": "true", "subnetMask": "255.255.255.255", "iPAddress": "10.10.10.10", "dhcpEnabled": "true"}]
after I use the following function I got the following dictionary which I really don't know how to access
NSDictionary * res = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
here is a picture of the dictionary
http://www11.pic-upload.de/09.11.14/5n4hdg3eh84q.png
How can I access for example the defaultGateway in the first dictionary?
You have a small logical error in your example. The expression [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; returns an NSArray and not and NSDictionary. So, first you should change this part to:
NSArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
I know it's an array because your JSON string contains an array of two JSON objects. NSJSONSerialization will transform JSON arrays into objects of type NSArray and JSON objects into objects of type NSDictionary.
If you're not sure what your JSON contains, you can do the following:
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if ([result isKindOfClass:[NSArray class]]){
// do something with the array
}
else if ([result isKindOfClass:[NSDictionary class]]){
// do something with the dictionary
}
As for your question, you can access the data in an NSDictionary by providing a key, which you can do in two ways:
NSString *gateway = [dictionary objectForKey:#"defaultGateway"];
or even faster:
NSString *gateway = dictionary[#"defaultGateway"];
Coming back to your example, to access the defaultGateway from the first of your two JSON objects, you can do the following:
NSArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; // parse the JSON and store in array
NSDictionary *dict = result[0]; // take the first of the two JSON objects and store it in a dictionary
NSString *gateway = dictionary[#"defaultGateway"]; // retrieve the defaultGateway property

iOS parsing a jsonDictionary

I am from php domain, and now learning ios coding. I want to make a view with one part showing user info, and a table showing friends details.
I can get the json Logged correctly.
My json looks like this:
{"Me":
{"username":"aVC",
"userID":1
},
"Friends":
[{"username":"Amm",
"userID":2
},...
]
}
Here is what I use.
NSError *error;
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *json = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jS: %#", json);
this works fine. I want to seperate the two sections (Me, and friends), and then use it to fill tables. Can someone throw some ideas?
NOTE: I am not using any frameworks. Just NSJSONSerialization.
Try adding this code after obtaining the json dictionary:
NSDictionary *me = [json objectForKey:#"Me"];
NSArray *friends = [json objectForKey:#"Friends"];
This should let you pull the information from the #"Me" and #"Friends" into separate variables.

NSJSONSerialization returning null

I am writing an app which is supposed to read JSON data from a remote web service. the URL is in the format "something.action".
I use dataWithContentsofURL to download the JSOn data from the service and I see that this function does return back some data.
Using this data I call the function NSJSONSeraiization, but the response of this is null.
Basically, I am using the code provided on http://www.raywenderlich.com/5492/working-with-json-in-ios-5. The only difference is that I am fetching data from a remote server and my URL is of the form "something.action".
I am not able to figure out what is going wrong here.
Check a JSON viewer like http://jsonviewer.stack.hu/ to confirm if the JSON returned is correct or not.
Do an NSLog of the string obtained from the NSData you receive and use it with the viewer. If there are any issues, you know why the object is not serialized.
Check the response you get is a properly-formatted JSON file, if it is check its class:
NSError *jsonError = nil;
NSJSONSerialization *myJSONObject = [NSJSONSerialization JSONObjectWithData:theNSDataObained options:NSJSONReadingMutableContainers error:&jsonError];
if(jsonError != nil){
NSLog(#"JSON Error: %#", jsonError);
return;
}
//An NSJSONSerialization object will either be an NSDictionary or
//an NSArray, figure out what it is:
NSLog(#"JSON class is: %#", [myJSONObject class]);
//if it's a NSDictionary:
if([myJSONObject isKindOfClass:[NSDictionary class]]){
NSDictionary *myJSONDictionary = (NSDictionary *) myJSONObject;
for(id key in myJSONDictionary){
id value = [myJSONDictionary valueForKey:key];
[value doStuff];
}
}
else //if it's a NSArray....

Resources