addObject in Array like xml structure - objective-c

Folks,
I have a Array similar to oneArray bellow, this file is already ready and functional. I want to mount this array dynamic, like addObject, but how can I add a descs value and into it test values ?
Tks for help.
#property (strong, nonatomic) NSArray *oneArray;
self.oneArray = #[ #{ #"desc": #"desc1",
#"descs": #[ #{ #"test": #"test1" },
#{ #"test": #"test2" }
]
},
#{ #"desc": #"desc2",
#"descs": #[ #{ #"test": #"test3" },
#{ #"test": #"test4" },
#{ #"test": #"test5" }
]
}
];

NSArray can't have Associative name. If you want to have associative name better use NSDictionary.

You can use for this purpose json structure and NSJSONSerialization, e.g. file content would be
[
{
"desc": "desc1",
"descs": [
{
"test": "test1"
},
{
"test": "test2"
}
]
},
{
"desc": "desc2",
"descs": [
{
"test": "test3"
},
{
"test": "test4"
},
{
"test": "test5"
}
]
}
]
And code:
NSError *error;
NSData *contentFile = [NSData dataWithContentsOfFile:#"my.json"];
NSArray *descs = [NSJSONSerialization JSONObjectWithData:contentFile options:kNilOptions error:&error];

Related

how to gat a value from an array which contain in an object and object already in an array while using json response?

[
{
"result": 1,
"max_qty": "10",
"msg": [
{
"product_id": "39",
"product_name": "Cabbage",
"product_price": "18",
"product_image": "product/39.jpg",
"product_description": "Fresh Cabbage",
"product_category": "1",
"product_qty": [
{
"quantity_id": "3",
"quantity_name": "500 gm",
"value": "500",
"quantity_status": "1"
},
{
"quantity_id": "4",
"quantity_name": "1 Kg",
"value": "1000",
"quantity_status": "1"
}
In this "msg" which is an array and contains value in form of object but "product_qty" again an array which is under the object,now how can i fetch the elements value of product_qty ]1
just used this
if([array containsObject dict])
{
already in your array
}
else
{
not in your array
}
Updated Code:
NSDictionary *mainDic = [arrResponse objectAtIndex:0];
NSArray *arrMsg = [mainDic valueForKey:#"msg"];
for (NSDictionary *dicSub in arrMsg) {
NSArray *arrProdQuality = [dicSub valueForKey:#"product_qty"];
for (NSDictionary *dicQuality in arrProdQuality) {
NSLog(#"quantity_name %#",[dicQuality valueForKey:#"quantity_name"]);
}
}
You need to fetch key value like this:
NSDictionary *dictProducts = array[0]; // From Main Array.
NSArray *allProduct = dictProducts[#"msg"]; // Form Dictionary.
NSDictionary *firstProduct = allProduct[0];
NSLog(#"Product Qty : %#", firstProduct[#"product_qty"]); // Here you can get product_qty array.
Hope this will helps.

How to map an array of arrays in Mantle

Anybody got an idea of how to map this response to a mantle object?
I need to get these to an NSArray of custom classes. But the Mantle documentation has no mention on how to do this.
Thanks in advance.
[
[
{
"plu_id": "1744",
"name": "With egg",
"price": "2.00",
"group": null
}
],
[
{
"plu_id": "1745",
"name": "add roast chicken",
"price": "3.00",
"group": "1"
},
{
"plu_id": "1749",
"name": "add beef",
"price": "4.00",
"group": "1"
}
]
]
Please try the below snippet mentioned for an identical issue
+ (NSValueTransformer *)allRowsJSONTransformer
{
return [MTLValueTransformer transformerWithBlock:^id(NSArray *inSectionJSONArray) {
NSMutableArray *sectionArray = [[NSMutableArray alloc] initWithCapacity:inSectionJSONArray.count];
for( NSArray *section in inSectionJSONArray )
{
NSError *error;
NSArray *cardItemArray = [MTLJSONAdapter modelsOfClass:[CKMCardItem class] fromJSONArray:section error:&error];
if( cardItemArray != nil )
{
[sectionArray addObject:cardItemArray];
}
}
return sectionArray;
}];
}

How to extract particular elements from JSON [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a JSON file that looks like this in my project:
{
"city": [
{
"NewYork": [
{
"url_id": "63",
"title": "someTitle"
},
{
"url_id": "62",
"title": "someOtherTitle"
}
],
"Boston": [
{
"url": "68",
"title": "someTitle"
}
]
.
.
.
Then I'm trying to go through it in Objective-C and create an array of only the names of the cities. I'm able to log the whole JSON, or the properties of "New York", but not just the names.
Is my JSON wrong or am I doing something wrong in the code?
Edit: I forgot to mention that some cities could have multiple id's and titles so I believe creating dictionaries is out of question? Also I have the data in a file so I'm not creating it in the code.
This JSON doesn't seem quite right. The cities value should just be a dictionary:
{
"cities" : {
"Boston" : [
{
"url_id" : "63",
"title" : "someTitle"
},
{
"url_id" : "62",
"title" : "someOtherTitle"
}
],
"New York" : [
{
"url_id" : "63",
"title" : "someTitle"
},
{
"url_id" : "62",
"title" : "someOtherTitle"
}
]
}
}
If you wanted to get the array of city names from the above JSON, you'd convert this to a dictionary and use allKeys of the value returned from the cities key:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSArray *cityNames = [dictionary[#"cities"] allKeys];
Personally, I think it would be better to make your cities value in the JSON an array of dictionaries, where the city name is an attribute of the dictionary:
{
"cities" : [
{
"name" : "New York",
"urls" : [
{
"url_id" : "63",
"title" : "someTitle"
},
{
"url_id" : "62",
"title" : "someOtherTitle"
}
]
},
{
"name" : "Boston",
"urls" : [
{
"url_id" : "63",
"title" : "someTitle"
},
{
"url_id" : "62",
"title" : "someOtherTitle"
}
]
}
]
}
In which case, you'd retrieve the city names like so:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSArray *cityNames = [dictionary[#"cities"] valueForKey:#"name"];
But the JSON proposed in the question seems to have some redundant [, IMHO. And I think the key name of city is misleading because it contains a number of cities, so I'd instead suggest cities.
You must create first a dictionary that contains city key and city key must assign to an array.
NSDictionary *newYorkDict = {
#"url_id":#"63",
#"title":#"someTitle"
};
NSDictionary *bostonDict = {#"url_id":#"63",
#"title":#"someTitle"
};
NSArray *newYorkArray = [newYorkDict];
NSArray *bostonArray = [bostonDict];
NSDictionary *dict = {
#"New york":newYorkArray,
#"Boston":bostonArray
};
NSArray *cityArray = [dict];
NSDictionary *mainDict = {#"city":cityArray};

How to filter a multi-dimensional array

I have the following multi-dimensional array (stripped and reduced for clarity)
[
{
"type": "type1",
"docs": [
{
"language": "EN"
},
{
"language": "DE"
},
{
"language": "EN"
}
]
},
{
"type": "type2",
"docs": [
{
"language": "EN"
}
]
},
{
"type": "type3",
"docs": [
{
"language": "FR"
},
{
"language": "DE"
},
{
"language": "DE"
}
]
}
]
I want to filter it, so only docs objects with a language of DE are shown. In other words, I need this:
[
{
"type": "type1",
"docs": [
{
"language": "DE"
}
]
},
{
"type": "type2",
"docs": []
},
{
"type": "type3",
"docs": [
{
"language": "DE"
},
{
"language": "DE"
}
]
}
]
My array is initially created by the following piece of code:
NSMutableArray *docsArray;
[self setDocsArray:[downloadedDocsArray mutableCopy]];
I have tried looping the array and removing unwanted objects. I have tried looping the array and copying wanted objects to a new array. I have tried using NSPredicate instead of looping, all of which had very little success.
Can anyone point me in the right direction?
Thanks in advance.
You should iterate over the array to get the dictionaries containing the arrays to filter:
NSArray* results;
NSMutableArray* filteredResults= [NSMutableArray new]; // This will store the filtered items
// Here you should have already initialised it
for( NSDictionary* dict in results)
{
NSMutableDictionary* mutableDict=[dict mutableCopy];
NSArray* docs= dict[#"docs"];
NSPredicate* predicate= [NSPredicate predicateWithFormat: #"language like 'DE'"];
docs= [docs filteredArrayUsingPredicate: predicate];
[mutableDict setObject: docs forKey: #"docs"];
[filteredResults addObject: mutableDict];
}

IPhone Google JSON Geocoing Parsing

I am unsure how to parse nested JSON output. I am using Googles JSON geocoding and trying to extract the coordinates. I am thinking I need another level of parsing. My code that does not work:
hostStr = [hostStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *hostURL = [NSURL URLWithString:hostStr];
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:hostURL];
self.jsonArray = [jsonString JSONValue];
NSDictionary *coordinates = [self.jsonArray objectForKey:#"id:p1"];
NSLog(coordinates);
NSString *point = [coordinates objectForKey:#"Point"];
NSLog(point);
The JSON:
{
"name": "11111 WASHINGTON AVE # 116 SAN PEDRO, CA 91111",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [ {
"id": "p1",
"address": "11111 Washington Ave, San Pedro, CA 91111, USA",
"AddressDetails": {
"Accuracy" : 8,
"Country" : {
"AdministrativeArea" : {
"AdministrativeAreaName" : "CA",
"Locality" : {
"LocalityName" : "San Pedro",
"PostalCode" : {
"PostalCodeNumber" : "91111"
},
"Thoroughfare" : {
"ThoroughfareName" : "Washington Ave"
}
}
},
"CountryName" : "USA",
"CountryNameCode" : "US"
}
},
"ExtendedData": {
"LatLonBox": {
"north": 37.7026153,
"south": 37.6999173,
"east": -122.1393925,
"west": -122.1420904
}
},
"Point": {
"coordinates": [ -122.1407313, 50.7012704, 0 ]
}
} ]
}
It looks like you're unclear on how to reach into nested objects in the parsed JSON. I assume you're using JBJson (formerly Json-Framework) to get that JSONValue category on NSString, yes? If so, it's parsed the whole deal, you just have to walk it.
The first helpful this online json visualizer: http://jsonviewer.stack.hu/
Paste your raw JSON into that to see the whole tree structure of it.
Then, you should understand your'e going to to get an NSDictionary that has NSDictionaries and NSArrays in its values. So it's not "id: p1" you're digging into. If you want those coordinates, the coordinates array is at the path Placemark[0].Point.coordinates.
It's going to look more like:
NSArray *placemarks = [self.jsonArray objectForKey:#"Placemark"];
NSDictionary *mark = [placemarks objectAtIndex:0];
NSDictionary *point = [mark objectForKey:#"Point"];
NSArray *coordinates = [point objectForKey:#"coordinates"];
A clever person who has worked in Obj-c more recently than I might be able to walk that with an keypath or something, but I did it this way to show you the nested objects you're really navigating here.