Parsing json having multiple arrays - ios

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

Related

How to sort a jSON file alphabetically and assign them to the corresponding letter to use sectionIndexTitlesForTableView/ sectionForSectionIndexTitle

This is my first time asking a question here, so please excuse my lack of writing etiquette.
I have a jSON data file which looks like this:
[ {
"category": "Feline",
"text": "CAT",
"definition": "Meow" },
{
"category": "Mammal",
"text": "DOG",
"definition": "Bark" },
{
"category": "Insect",
"text": "ANT ",
"definition": "buzz" },
{
"category": "Insect'",
"text": "MOSQUITO ",
"definition": "buzz" },
{
"category": "Number'",
"text": "10",
"definition": "ten" }
]
I am importing it as follows, the dataList is a NSMutableArray, I am also confused if using the MutableArray is good or if I should be using NSDictionary?:
-(void)readDataFromFile {
NSString * filePath =[[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
NSError * error;
NSString* fileContents =[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(error)
{
NSLog(#"Error reading file: %#",error.localizedDescription);
}
self.dataList = (NSMutableArray *)[NSJSONSerialization
JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
}
I would like to sort the JSON data alphabetically according to 'text'
and also I am using sections and index list. I mainly followed https://www.appcoda.com/ios-programming-index-list-uitableview/ tutorial.
I am confused on how to sort the JSON data and also divide them into sections of alphabets and also iOS contacts accounts for numbers by putting them under '#' section.
How do i accomplish that as well?
Thanks in advance!
In the below code i've made an 2D array of 27 elements(1 for numeric
and 26 for alphabets) and then placed the value according to the
string initial character. This piece of code worked for me.Hope so it
will work for you too :)
for (int section = 0; section < 27; section++)
{
[arrSections addObject:[NSMutableArray array]];
}
for (NSDictionary *item in SampleDictionary)
{
NSString *KeyValue = [item[#"DictionaryKEy"] capitalizedString];
*//In your case its Text*
int ascii = (int)[KeyValue characterAtIndex:kZero];
if (ascii >= 65 && ascii <= 90)
{
[arrSections[(ascii - 64)] addObject:item];
}
else
{
[arrSections[0] addObject:item];
}
}

how to call for json with conditions in ios 9, using objective C

This is my json web response response.
-Itinerary: [
-{
ID: "1",
ValueOne: "2473.05",
ValueTwo: "368.95"
},
-{
ID: "2",
ValueOne: "2453.05",
ValueTwo: "308.95"
}
],
-Details :[
-{
ID:"1",
FirstName:"Graham",
LastName:"Json"
},
-{
ID:"1",
FirstName:"Anuradh",
LastName:"Stackoverflow"
}
]
What should be the response object type.I do like this, is it correct or it does not matter whatever the type
NSDictionary *Results = (NSDictionary *)responseObject;
then I get the response.now what I want is to get itinerary details and
get the Details only where the itinerary ID is equal to Details ID .how can I do that.
NSArray *Itinerary = [Resulsts objectForKey=#"Itinerary"];
NSArray *Itinerary = [Resulsts objectForKey=#"Detailss"];
for(NSDictionary *itinry in Itinerary)
{
NSString *Iid = [itinry objectForKey="ID"];
NSString *ValOne = [itinry objectForKey="ValueOne"];
//like this I'm getting values
//then here I want to get all details which it's `itinerary` `ID` equal to `Details` `ID`.how can I do that.
}
then here I want to get all details which it's itinerary ID equal to Details ID.how can I do that.
Please try this code Hope it will work for you
NSArray *Itinerary = [Resulsts objectForKey=#"Itinerary"];
NSArray *dTinerary = [Resulsts objectForKey=#"Detailss"];
for(int i=0; i<Itinerary;i++)
{
NSString *iID=[[Itinerary objectAtIndex:i] objectForKey:#"ID"];
NSString *dID=[[dTinerary objectAtIndex:i] objectForKey:#"ID"];
if ([iID isEqualToString:dID])
{
// do your thinks here
NSLog(#"%#",[[Itinerary objectAtIndex:i] objectForKey:#"ValueOne"]);
// break;
}
// NSString *Iid = [itinry objectForKey="ID"];
// NSString *ValOne = [itinry objectForKey="ValueOne"];
//like this I'm getting values
//then here I want to get all details which it's `itinerary` `ID` equal to `Details` `ID`.how can I do that.
}

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.

Parsing JSon Data FlightAware

I am using the flight aware service to get flight information but I am having trouble getting the data in a way I can use.
Json response is:
{
"AirlineInfoResult": {
"name": "US Airways",
"shortname": "US Airways",
"callsign": "Cactus",
"location": "Tempe, AZ",
"country": "United States",
"url": "http://www.usairways.com/",
"phone": "+1-800-428-4322"
}
}
And this is the code I am using but nothing is returned
NSMutableDictionary * routeRes;
routeRes = [json objectForKey: #"AirlineInfoResult"];
NSMutableArray * res;
res = [json objectForKey: #"url"];
for (NSMutableDictionary * flight in res) {
NSLog(#"actual arrival time= %#", [flight objectForKey: #"url"]);
}
What am I missing in getting this data?
change below line:
res = [json objectForKey:#"url"];
with
res = [routeRes objectForKey:#"url"];

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