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
Related
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"];
I need to parse a json and get the key value pairs in the same sequence as they are present in response.
Currently what i'm doing is
-(instancetype)initWithJson:(NSDictionary *)responseDict {
if (self = [super init]){
NSArray *tempArray = [[NSArray alloc] init];
NSArray *roomSizesForAcArray = [responseDict valueFromDictionaryWithNSNullCheck:#"roomSizesForAc"];
NSArray *loadChartForInverterArray = [responseDict valueFromDictionaryWithNSNullCheck:#"loadChartForInverter"];
if(roomSizesForAcArray && roomSizesForAcArray.count>0){
self.isInverterChart=false;
tempArray=roomSizesForAcArray;
}
else if(loadChartForInverterArray && loadChartForInverterArray.count>0){
self.isInverterChart=true;
tempArray=loadChartForInverterArray;
}
self.arrayOfChartSizeObjects=tempArray;
if(tempArray && tempArray.count>0){
//Temp array first object is a dictionary which i need to parse sequentially
self.arrayOfKeys = [[tempArray objectAtIndex:0] allKeys];
//This array of keys is random every time and not sequential
}
}
return self;
}
I need to someway parse the dictionary [tempArray objectAtIndex:0] maintaining the order of keys in init.
Not clear what you want, you want dictionary while you are already parsing the dictionary. To get dictionary from the JSON use below code.
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:receiveData options:kNilOptions error:&error];
To get all the keys and then retrieve the details use
NSArray *sortedKeys = [[jsonDict allKeys]
Once you have keys then get the details
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
Dictionaries are unordered collections. You say "...maintaining the order of keys in init". There is no such thing.
JSON "Objects", the JSON equivalent of a NSDictionaries/Swift Dictionaries, have the same issue.
Some JSON libraries will preserve the order in which key/value pairs are submitted to be sent, but you should not depend on that. The JSON protocol does not guarantee it.
Once you receive JSON data and convert it to an NSDictionary/Dictionary, the order in which the key/value pairs is sent is lost. The only way I know of to preserve the (already unreliable) order of the key/value pairs from the original JSON data stream is to parse the JSON yourself rather than deserializing it using NSJSONSerialization.
If you want your data in a particular order, you should use an array as the container object to send it. You can send an array of key/value pairs if you need to.
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
Thank you reading my post, I known this topic was asked so many time, and I had saw that but no luck...
I want to parse a simple JSON string, as followings:
[
{
"id":"1",
"name_en":"Photography",
"subchannels":[
{
"id":"4",
"name_en":"John"
},
{
"id":"18",
"name_en":"Sam"
}
]
},
{
"id":"7",
"name_en":"Equipment",
"subchannels":[
{
"id":"25",
"name_en":"ABC Company"
},
{
"id":"40",
"name_en":"CDE Company"
}
]
}
]
It had convert this string to NSDictionary
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *testDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&e];
Then I list the Dictionary Key
for(id key in testDic) {
NSLog(#"%#", key);
}
The result is the entire record as the Dictionary Key, so I can't use [testDic objectForKey:key] to retrieve the value.
How can I get the first row name_en and the second row subchannels value?
(is it possible to retrieve easily like xpath in XML?)
Thank you for helping.
First of all. The root object of your model is NSArray object - not `NSDictionary. '[]' means array and {} means dictionary.
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&e];
for (NSDictionary *entry in dataArray) {
NSString *name = entry[#"name_en"];
NSArray *subchannels = entry[#"subchannels"]; //array of dictionaries
NSLog(#"Name %s", name);
for (NSDictionary *subchannel in subchannels) {
NSLog(#"Subchannels name %# id: %d", subchannel[#"name"], [subchannel[#"id"] integerValue]);
}
}
If you want to perform advances JSON parsing I encourage you to look at Mantle github project.
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.