How to parse JSON multi-array - ios

I need to parse the JSON file provided by Google Maps API
Then i use the AFNetworkingRequestHow to get the JSON response.
I built this dictionary:
NSDictionary *jsonDict = (NSDictionary *) JSON;
NSArray *rows = [jsonDict objectForKey:#"rows"];
But now, how can i reach the first value field of duration tag?
JSON File to parse:
{
"destination_addresses" : [ "San Francisco, CA, USA", "Victoria, BC, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada", "Seattle, WA, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,527 km",
"value" : 1527251
},
"duration" : {
"text" : "15 hours 0 mins",
"value" : 54010
},
"status" : "OK"
},
{
"distance" : {
"text" : "112 km",
"value" : 111906
},
"duration" : {
"text" : "3 hours 1 min",
"value" : 10885
},
"status" : "OK"
}
]
}
}

Try
NSDictionary *jsonDict = (NSDictionary *) JSON;;
NSArray *rows = jsonDict[#"rows"];
NSDictionary *row = rows[0];
NSArray *elements = row[#"elements"];
NSDictionary *element = elements[0];
NSDictionary *duration = element[#"duration"];
NSInteger value = [duration[#"value"] integerValue];

[json objectForKey:#"elements"]
is an NSArray. You can't initialize an NSDictionary directly with an array.
(in JSON, { and } denote key-value pairs, like NSDictionary, whereas [ and ] delimit ordered lists like NSArray, that's why the mapping is done as it is...)
Following thinks can you understanding for development time so it may help lot.

You can use the following code:
NSString *valueString = [[[[[rows objectAtindex:0]objectForKey:#"elements" ]objectAtindex:0]objectForKey:#"duration"] objectForKey:#"value"];
//if you want integer value
NSInteger value = [valueString integerValue];

Related

Filter NSArray of NSDictionary , where the dictionary is of type <key , NSDictionary>

I have a NSArray like this
[ {
"268" : { "name" : "abc", "age" : "28"} }, {
"267" : { "name" : "xyz","age" : "25"} } ]
Now I want to filter it on behalf of keys (means 268 , 267 ).
Eg : If user search for 7 then it need to show
[ { "267" : { "name" : "xyz","age" : "25"} } ]
let filterText : String = "7"
let array : [Dictionary<String,Any>] = [ ["268" : [ "name" : "abc", "age" : "28"]], [ "267" : [ "name" : "xyz","age" : "25"] ] ]
let result = array.filter { (dictinory) -> Bool in
if let firstKey = dictinory.keys.first {
return firstKey.contains(filterText)
}
return false
}
You can use NSPredicate with block in Objective-C to filter it:
NSString *searchText = #"8";
NSArray *data = #[#{ #"268" : #{ #"name" : #"abc", #"age" : #"28"} }, #{ #"267" : #{ #"name" : #"xyz",#"age" : #"25"}}];
NSPredicate *predicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
NSDictionary *dict = (NSDictionary *)obj;
NSString *key = dict.allKeys.firstObject;
return [key containsString:searchText];
}];
NSArray *filteredData = [data filteredArrayUsingPredicate:predicate];

I am trying to parse such a json in which use many arrays and dictionary. How to parse it in iOS?

I'm able to parse first three values. The nested values in dayWiseTimeSheet section i want to parse.
{"TimeSheet":
[
{"day":"10-5-2016",
"totalTravelTime":"1.40hrs",
"totalWorkTime":"6hrs",
"dayWiseTimeSheet": [{
"taskId": "101",
"travelingTime": "40 mins",
"workingTime": "3 hrs"
}, {
"taskId": "102",
"travelingTime": "1 hr",
"workingTime": "3 hrs"
}]
},
{"day":"11-5-2016",
"totalTravelTime":"1.40hrs",
"totalWorkTime":"6hrs",
"dayWiseTimeSheet": [{
"taskId": "101",
"travelingTime": "50 mins",
"workingTime": "5 hrs"
}, {
"taskId": "102",
"travelingTime": "3 hr",
"workingTime": "7 hrs"
}]
}
]
}
The code i have used is
for (NSDictionary *bpDictionary in books )
{
TimesheetInfo *tableObject = [[TimesheetInfo alloc]initwithday:
[bpDictionary objectForKey:#"day"]
totalTravelTime:[bpDictionary objectForKey:#"totalTravelTime"]
totalWorkTime:[bpDictionary objectForKey:#"totalWorkTime"]
}
Please try this :
NSMutableArray *allDayWiseTimeSheet = [NSMutableArray new];
for (NSDictionary *bpDictionary in books )
{
TimesheetInfo *tableObject = [[TimesheetInfo alloc]initwithday:[bpDictionary objectForKey:#"day”]]]
totalTravelTime:[bpDictionary objectForKey:#"totalTravelTime"]
totalWorkTime:[bpDictionary objectForKey:#"totalWorkTime"]
NSArray *dayWiseTimeSheet = [bpDictionary objectForKey:#“dayWiseTimeSheet”];
for(NSDictionary *info in dayWiseTimeSheet)
{
[allDayWiseTimeSheet addObject:info];
NSLog(#“%#”,[info valueForKey:#“taskId”]);
NSLog(#“%#”,[info valueForKey:#“travelingTime”]);
NSLog(#“%#”,[info valueForKey:#“workingTime”]);
}
}
Parse the 3rd Key's Value into a dictionary with Data Type of Array with Anyobject Data Type
Later get every object from array into a entity class.
Let dict = response.objectforkey("dayWiseTimeSheet")
if the data is a json ,maybe you must translate the json to nsdictionary ,then you can get the NSarry for the collecttion of model.
Given the JSON data the following code will parse "dayWiseTimeSheet" data. The type of the json should be dictionary not an array.
for (id obj in [[json valueForKey:#"TimeSheet"] valueForKey:#"dayWiseTimeSheet"]) {
NSLog(#"%#",[obj valueForKey:#"taskId"]);
NSLog(#"%#",[obj valueForKey:#"travelingTime"]);
NSLog(#"%#",[obj valueForKey:#"workingTime"]);
}

How should i parse this JSON?

What would be the best way to parse this JSON object into a data object in Objective C?
{
"Properties" : {
"Property1" : {
"min" : 70.0,
"max" : 70.0
},
"Property2" : {
"min" : 0.41,
"max" : 0.41
},
"Property3" : {
"min" : 0.41,
"max" : 0.41
},
"Property4" : {
"min" : 0.41,
"max" : 0.41
}
}
The name "properties" will remain constant, but the name of properties inside this can change and so can the number of properties. For example, this could be;
{
"Properties":
"RandomNameOfProperty" : {
"min" : 0.41,
"max" : 0.41
},
"RandomNameOfProperty2" : {
"min" : 0.41,
"max" : 0.41
}
}
}
Edit: Corrected JSON format.
NSMutableDictionary *json = [[NSMutableDictionary alloc] init];
json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: &e];
where data is your json data
Here is how you can transform you JSON to Objective-C
NSString *jsonString = #"{"name": "My name" ....}"
NSData *data = [#" " dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *json = [[NSMutableDictionary alloc] init];
NSError *er;
json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: &er];
MyClassModel *my = [[MyClassModel alloc] init];
my.name = json[#"name"];
my.age = [json[#"age"] integerValue];
my.type = json[#"type"];
There are also many libraries that does dynamic parsing and transformation for you.
JSONModel is really good one. With it you code would look like this -
NSString* json = #"{"name": "My name" ....}" //(fetch here JSON from Internet)
NSError* err = nil;
MyClassModel* country = [[MyClassModel alloc] initWithString:json error:&err];

Mapping array to dictionary using object in array as key

I'm using RestKit in my iOS app and I can't seem to get this to work. I have the following JSON array:
{
"id" : 1,
"streamable" : true
},
{
"id" : 2,
"streamable" : true
},
{
"id" : 3,
"streamable" : true
}
I would like to end up with a dictionary looking like this:
{
"1" : {
"id" : 1,
"streamable" : true
},
"2" : {
"id" : 2,
"streamable" : true
}
}
Where I use the id value as the dictionary's key. How would I map this using RestKit?
Assume, you have array of Disctionaries , iterate through the dictionaries and find for the id make this a new Dictionary
For Instance :
NSArray *arrDictionaries = // .....
NSDictionary *result =[[NSDictionary alloc]init];
for(NSDictionary *dict in arrDictionaries){
NSstring *key = [dict objectForKey:#"id"];
[result setObject:dict forKey:key];
}
Note : I've not tested

iOS JSON parse trouble

How should I parse JSONs with format:
{
"1": {
"name": "Бекон",
"unit": "гр."
},
"2": {
"name": "Бульон куриный",
"unit": "ст."
}
}
and:
{
"recipeCode" : "00001",
"inCategory" : "12",
"recipe" : "Зимний тыквенный суп",
"difficulty" : 2,
"personCount" : 4,
"prepHour" : 1,
"prepMin" : 30,
"comments" : "При подаче добавить сметану, крутоны и присыпать сыром",
"ingredients" : {
"2" : 3,
"11" : 2,
"13" : 1,
"14" : 2,
"19" : 1
}
}
The second one I even didn't try... But with the first one I have some problems. I do this:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Ingredients" ofType:#"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
NSDictionary *ingredients = [NSJSONSerialization JSONObjectWithData:myData options:kNilOptions error:&error];
and than I have ingredient dictionary with two key/value pairs. Both of them contains key "1" and value "1 key/value pairs" and nothing about "name" or "unit" values.
Any help how to correctly parse such JSONs
You are parsing it correctly,and what you will have output will be there in the dictionary
The parsing gives output as objects as NSDictionary and array as NSArray
so in your case the key 1 and key 2 have value a NSDictionary itself
NSDictionary *dict1 = [ingredients objectForKey:#"1"];
NSDictionary *dict2 = [ingredients objectForKey:#"2"];
and value as
NSString *name=[dict1 objectForKey:#"name"];
NSString *unit=[dict1 objectForKey:#"unit"];

Resources