iOS JSON parse trouble - ios

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"];

Related

Parsing json having multiple arrays

I am stuck with JSON parsing in my code. I tried a lot but could not figure out what is going wrong.
This is my JSON response
[{
"order": {
"transaction_id": "bFnRjTPYfD",
"status": 0,
"created_at": "2015-04-22 09:35:35"
}
}, {
"order_items": [{
"item_id": 1,
"item_name": "Potato",
"item_description": null,
"item_salesprice": 14,
"item_imagepath": "\/uploads\/veggies\/potato.jpg",
"order_quantity": "4 Kg",
"order_price": 69.99
}, {
"item_id": 2,
"item_name": "Tomato",
"item_description": null,
"item_salesprice": 18,
"item_imagepath": "\/uploads\/veggies\/tomato.jpg",
"order_quantity": "6 Kg",
"order_price": 79.99
}]
}]
I want to extract transaction id and item name. Can you please help me with this?
Update Answer:
NSDictionary *Order=[JSONData ValueForKey:#"Order"];
NSString *transaction_id=[Order ValueForKey:#"Transaction_id"];
You can get transaction_id by this way,
NSDictionary *OrderJson=[jsonArray objectAtIndex:0];
NSDictionary *OrderDic = [OrderJson valueForKey:#"order"];
NSString *transactionId=[OrderDic objectForKey:#"transaction_id"];
ItemNames are in array, you can get it by for loop, or predicates, Here I show you with for
NSDictionary *order_itemsJson=[jsonArray objectAtIndex:1];
NSArray *item=[order_itemsJson objectForKey:#"order_items"];
for (NSDictionary *dic in item) {
NSLog(#"%#",[dic valueForKey:#"item_name"]);
}
Enjoy Coding !!
Do the following things, you will get output.
NSString* transectionId = [[[arrayResponse objectAtIndex:0] valueForKey:#"order"] valueForKey:#"transaction_id"];
NSLog(#"transectionId : %#",transectionId);
NSArray* arrayInner = [[arrayResponse objectAtIndex:1] valueForKey:#"order_items"];
for (int i=0; i<arrayInner.count; i++) {
NSDictionary* dictInner = [arrayInner objectAtIndex:i];
NSString* itemName = [dictInner valueForKey:#"item_name"];
NSLog(#"Item Name : %#",itemName);
}
Here you will get transaction_id and item_name
Hope this help you.
Try it.. For Transaction id..
NSDictionary *Order=[JSONData ObjectForKey:#"Order"];
NSString *transaction_id=[Order ValueForKey:#"Transaction_id"];
and For item_id try,...
NSDictionary *item=[JSONData objectForKey:#"order_items"];
NSArray *item_id=[Order ValueForKey:#"item_name"];

How to parse Dynamic changes in json value. Dictionary with 2 nested dic & then array and then dic again

Dictionary with two nested dictionary and then array and then dictionary again how can i write code generally for objective c ,iOS 8;
{
"brands": {
"Clinique": {
"Foundation": {
"Even Better Makeup SPF 15": {
"productName": "Even Better Makeup SPF 15",
"colors": [
{
"id": "30816",
"client_id": "1422956000sjdaC",
"product_id": "190",
"shade_name": "Alabaster",
"shade_code": "#F0C9AE",
"color_id": null,
"image_url": "",
"price": "",
"offer": "",
"created_by": "1422956000sjdaC",
"created_date": "2015-03-06",
"sku_id": "",
"product_web_url": "",
"brand_id": "Clinique",
"product_name": "Even Better Makeup SPF 15",
"makeup_type": "Foundation",
"color_family": "cool"
},
As I can see, your JSON response is sending Product details, so the
"brands": {
"Clinique": {
"Foundation": {
will remain same always, and the response below it will change according to products.
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *productsDict = [[jsonDictionary objectForKey:#"brands"] objectForKey:#"Clinique"] objectForKey:#"Foundation"];
NSArray *keys=[productsDict allKeys];
for (int i = 0; i < keys.count; i++) {
NSDictionary *prodSingle = [productsDict objectForKey:[NSString StringWithFormat:#"%#",keys[i]]];
}
Now you have prodSingle, use this to get data of each product.
Note: Untested, I'll provide a tested version if this doesn't work.
EDIT:
As you said only brands key will remain constant and other will change dynamically,
you should do this :
So what you can do is create a NSDictionary with jsonData(response data) like this:
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
create a dictionary of brands
NSDictionary *brandsDict = [jsonDictionary objectForKey:#"brands"];
Now get all the keys:
NSArray *keys= [brandsDict allKeys];
Now use each key you got in Array to fetch data accordingly.

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];

sqlite command in iOS

Here I am using Sqlite Database for my Application, and my Database Table contains the column keyjson and values in rows are like below
{"filename":"21-01-3-02","label":""}
{"filename":"02-C-4-1","label":"17"}
{"filename":"14-L-3-2","label":"Nord Est"}
{"filename":"02-Z-5-1NouvelleIndustrieSectionValton","label":"1810"}
json data sas string
now I need to particular string that like
02
1
2
1NouvelleIndustrieSectionValton
from that particular column .
can anyone know the query for it,
Please replay me
&regards
You can do that without SQLite query. First, convert your JSON to a NSMutableArray :
NSData *data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
Then you can parse it easily as follow :
NSMutableArray *finalResult = [NSMutableArray array];
NSString *filename;
for (id e in res){
filename = [e objectForKey:#"filename"];
[finalResult addObject:[[filename componentsSeparatedByString:#"-"] lastObject]];
}
// Here we go, finalResult contains the values you want
The problem is that your "JSON" is not valid JSON. It should look like this if you want it works :
[
{
"filename": "21-01-3-02",
"label": ""
},
{
"filename": "02-C-4-1",
"label": "17"
},
{
"filename": "14-L-3-2",
"label": "Nord Est"
},
{
"filename": "02-Z-5-1NouvelleIndustrieSectionValton",
"label": "1810"
}
]

How to parse JSON multi-array

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];

Resources