How to get Array inside fields from JSON Structure in ios - ios

Hi i am beginner in ios and in my project i am integrating services with my app but i am struggling to integrate some service fields with my app
Please see below JSON structure there i want to get all "languages" Array inside elements but i am not understand how to get those fields please help me some one
Json stucture:-
- loans: [

 - {
id: 983381,
name: "America",
description: 
 {
languages: 
 [
"English"
]
},
},
- {
id: 983382,
name: "Jarmani",
description: 
 {
languages: 
 [
"Jarman"
]
},
},
- {
id: 983383,
name: "Rasya",
description: 
 {
languages: 
 [
"Rasya"
]
},
},
]
my code:-
NSMutableArray * array1 = [mainDictyionary objectForKey:#"loans"];
for (NSDictionary * obj in array1) {
MainArray = [obj objectForKey:#"languages"];
}
NSLog(#"so finally array values are %#",MainArray);

You want to
Declare MainArray as a NSMutableArray: MainArray = [[NSMutableArray alloc] init];
Now you will be adding the "languages" NSArrays to a 'mother-array', I'm guessing that is not what you want
So you want to iterate over the [obj objectForKey:#"languages"] array and call addObject on the MainArray for every NSString value you'll encounter in the [obj objectForKey:#"languages"]-iteration.
You'll end up with a mutable NSArray that has all the languages in it, as NSStrings

Actually you are getting the value upto languages and not upto "english" or anyother. And also you are assigning the values to MainArray, so it will not add all the values it will add last value of the loop.
NSMutableArray * array1 = [mainDictyionary objectForKey:#"loans"];
NSMutableArray *MainArray = [NSMutableArray alloc] init];
for (NSDictionary * obj in array1) {
NSDictionary *descriptionDictionary = [obj objectForKey:#"description"];
[MainArray addObject:[obj objectForKey:#"languages"]];
}
NSLog(#"so finally array values are %#", MainArray);

Related

Sort Dictionary of Array Using Predicate

I have a json dictionary
[
{
"allquestions": [
{
"question": "First question in 0th index"
},
{
"question": "Second question in 0th index"
}
]
},
{
"allquestions": [
{
"question": "First question in 1st index"
}
]
}
]
I need to get all values of key allquestions in single array using predicate.
I have tried so far is
NSPredicate *combinePagePredicate = [NSPredicate predicateWithFormat:#"allquestions == %#",#"someValue"];
What will be the value of someValue to solve my problem?
Not entirely sure what your trying to achieve. If you want a list of all of the questions in that dictionary then iterate through each dictionary separately and then the same for the questions. Add the questions to an array and then filter that array. Not tried this code out but it's a start.
NSMutableArray *questions = [[NSMutableArray alloc] init];
for (id i in dictionaryArray)
{
NSArray *arr = i[#"allquestions"];
for (id x in arr)
{
NSString *currentQuestion = [x objectForKey:#"question"];
[questions addObject:currentQuestion];
}
}

Create dictionary with dictionaries of arrays (sorted by a specific custom object property)?

The title may be confusing, apologies. Maybe someone can advise me on a more appropriate title.
I have a .json file structured as below.
"sections": [{
"title": "Locations",
"key": "location"
}],
"contacts": [{
"title": "Social Worker",
"name": "Mrs X",
"office": "xxxxxxxx",
"location": "Lisburn",
"department": "xxxxxxxx",
"telephone": "xxx xxxxxxxx"
},...
When parsing this, I create an array called contactsArray. I can then create AEContact objects from this array like so:
for (NSDictionary *contactDic in [contactsArray valueForKey:#"contacts"]) {
// Create AEContact objects
_contact = [[AEContact alloc] initWithDictionary:contactDic];
[contacts addObject:_contact];
}
self.contacts = [contacts copy];
In the self.contacts array, the value for the contact.location property is what I am interested in. I need to create separate arrays of related AEContact objects based on the location property, then map these to the location key in my contactArray dictionary
This is what I have tried so far:
NSMutableDictionary *locationsDic = [NSMutableDictionary new];
// Loop through contacts
for (int i = 0; i < self.contacts.count; i++) {
// Sort by location
if ([self.contacts[i] valueForKey:#"location"] == [[[contactsArray valueForKey:#"contacts"] objectAtIndex:i] valueForKey:#"location"]) {
[locationsDic setValue:self.contacts[i] forKey:[[[contactsArray valueForKey:#"contacts"] objectAtIndex:i] valueForKey:#"location"]];
}
}
And the output is:
{
Ballynahinch = "<AEContact: 0x15dda1fc0>";
Bangor = "<AEContact: 0x15dda2210>";
Lisburn = "<AEContact: 0x15dda1c70>";
...
}
When an AEContact object has the same location, it sets it as another key/value in the dictionary and overwrites the previous entry. What I need to happen is something like this:
{
Lisburn = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
Bangor = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
}
I'm not sure if the output should should/will look like the preview above, I can only assume as I have not yet achieved my goal. How can I create the related AEContact objects in an array and map them to location key in my locationsDic? Thanks.
The title (and the problem description) are a little tough to follow, but I think you're trying to index an array of (AEContact) objects by their location parameter.
We can clarify this just with some tighter naming and with a find-or-create pattern as we process the input.
NSDictionary *jsonResult = // the dictionary you begin with
NSArray *contactParams = jsonResult[#"contacts"];
NSMutableDictionary *contactsByLocation = [#{} mutableCopy];
for (NSDictionary *contactParam in contactParams) {
NSString *location = contactParam[#"location"];
// here's the important part: find the array of aecontacts in our indexed result, or
// create it if we don't find it
NSMutableArray *aeContacts = contactsByLocation[location];
if (!aeContacts) {
aeContacts = [#[] mutableCopy];
contactsByLocation[location] = aeContacts;
}
AEContact *aeContact = [[AEContact alloc] initWithDictionary:contactParam];
[aeContacts addObject:aeContact];
}
contactsByLocation will be what I think you're looking for.

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.
}

Multi level JSON reading and writing IOS8

So the last two days I have been struggling to get data from and to a JSON file, this is because it has multiple levels and the same names. I did not set up this file and can't change the structure so I have to get it working in the way it is. To Pharse JSON form a single level is no problem and it works fine, what I need is to get separate data block from "GOV" and "PRIV" then I need a data block "GENERAL" and "LOCAL" and within those I need to be able to get the "Hospital information as a block but also the separate values. Now I have been trying to get this done for two days and I know im doing something wrong but cant figure it out. I do get data back for example the "GOV" block but then in the output window it is showing a array with access data (<__NSCFArray 0x7fe711f58800>) and the output... I cant break up this output and that is what I need because every value needs to be in a text file in a tableview cell. I know { } denotes NSDictionary [ ] denotes NSArray and I have been reading a lot about JSON and I get the concept but There is little to non for me understandable info when it comes to multi level JSON and equal names (hospital) in this case. I have tried all the available option I could find here on StackOverflow but no succes. So if somebody can push me in the right way I will be gratefull.. part of the code:
NSURL *url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
_jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_AppListArray = [[NSMutableArray alloc] init];
NSArray *wrapper= [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *avatars = [wrapper objectAtIndex:0];
for(NSDictionary *apps in _jsonArray) {
if([[apps objectForKey:#"title"] isEqualToString:#"GOV"]){
NSDictionary*tmp = [apps objectForKey:#"hospital"];
_AppListArray = [tmp objectForKey:#"area"];
}
}
//returns error because _ApplistArray is an array and it can't read the data from the objectkey
for (int i = 0; i < _jsonArray.count; i++)
{
NSString *appName = [[_AppListArray objectAtIndex:i] objectForKey:#"hospitalname"];
NSString *appCondition = [[_AppListArray objectAtIndex:i] objectForKey:#"condition"];
NSString *app avgrating = [[_AppListArray objectAtIndex:i] objectForKey:#"avgrating"];
[_AppListArray addObject:[[Applist alloc]initWithAppName:appName andAppCondition:appCondition andAppURL:appURL]];
}
The _ApplistArray does return the 1ste Hospital data block but as an array and this is were I get stuck.. I need to get another level deeper.....Again the solution probably is easy but JSON is something I never worked with this is my first go. The JSON where I need to get the data from:
[
-{
-hospital: {
-area: [
-{
-hospital: [
-{
hospitalname: "ABC",
avgrating: "2,6",
condition: "UPDATE NEEDED",
},
-{
hospitalname: "DEF",
avgrating: "4,2",
condition: "FINE",
},
],
name: "GENERAL"
}
]
},
title: "GOV"
},
-{
-hospital: {
-area: [
-{
-hospital: [
-{
hospitalname: "GHI",
avgrating: "3",
condition: "INSTALL NEW",
},
-{
hospitalname: "JKL",
avgrating: "0",
condition: "NEW",
},
],
name: "LOCAL"
}
]
},
title: "PRIV"
}
]
Here you go.
NSArray *hospitals = [jsonArray objectForKey:#"mainKey"];// I assumed you getting with some key but change based on your requirement
for (NSDictionary *mainData in hospitals){ // Start of Main Hospital
NSDictionary *hospital = [mainData objectForKey:#"hospital"];
NSArray *areas = [hospital objectForKey:#"area"];
for(NSDictionary *area in areas){// Start of Area
NSArray *innerHospitals = [area objectForKey:#"hospital"];
for(NSDictionary *innerHospital in innerHospitals){
NSString *hospitalName = [innerHospital objectForKey:#"hospitalname"];
NSString *avgrating =[innerHospital objectForKey:#"avgrating"];
NSString *condition =[innerHospital objectForKey:#"condition"];
// Do What Ever you want here
}
NSString *name =[area objectForKey:#"name"];
}// End Of Area
NSString *title =[mainData objectForKey:#"title"];
} // End of Main Hospital
I haven't tested it. But i assume this will work. Have a try and let me know what happens.
The problem is that you need 2 for loops for each "Area".
Area is an Array (1st loop) and each hospital is another Array (2nd loop).
And inside each hospital element is the dictionary with the values you need.
ignoring loops this is how you get the first hospitalname(ABC) assuming _AppListArray has the contents of Area
NSString *appName = _AppListArray[0][#"hospital"][0][#"hospitalname"];
For each 0 you will replace it with the counters for the for loops.

Xcode - Getting object out of an array within an array

I have a JSON array(dictionary?) of objects that are themselves an array. I need to find a value within one of these arrays so that I can compare it later. Part of my JSON data:
[
{
"Name": "Exhibitor",
"Url": "api/congress/exhibitor",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Workshop",
"Url": "api/congress/workshop",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Speaker",
"Url": "api/congress/Speaker",
"ResourceType": "Data",
"LastMod": 1389106977
},
]
My method receives a table name as a parameter and returns a time stamp. How would I receive the time stamp (1389106977) for the table "workshop" for example? This seems so simple but I cannot work it out for 'nested' arrays/dictionaries.
Thanks,
edit:
This is the my code with trojanfoe's added to it.
NSError* localError;
NSMutableArray *syncDataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (syncDataArray)
{
NSNumber *lastMod = nil;
for (NSDictionary *dict in syncDataArray)
{
NSLog(#"current table is: %#", dict[#"Name"]);
if ([tableName isEqualToString:dict[#"Name"]])
{
lastMod = dict[#"LastMod"];
//break;
}
}
NSLog(#"LastMod = %#", lastMod);
}
else
{
NSLog(#"syncDataArray is empty");
}
This works perfectly and makes sense
The JSON data looks like an array of dictionaries, so you can iterate over the array and test for the "Name" entry:
NSArray *jsonData = ...; // You have converted JSON to Objective-C objects already
NSNumber *lastMod = nul;
for (NSDictionary *dict in jsonData) {
if ([#"Workshop" isEqualToString:dict[#"Name"]]) {
lastMod = dict[#"LastMod"];
break;
}
}
if (lastMod) {
// You found it
}
(Note I am not certain the type of object used to store the "LastMod" object, so you might need to do some debugging to find out).
EDIT If you make extensive use of this data you should immediately convert the JSON data into an array of (custom) model objects, which will make it easier to manipulate the data as your app becomes more complex.
You have an array for dictionaries so it would look something like :
NSNumber *timestamp = [[JSON objectAtIndex:index] objectForKey:#"LastMod"];
NSNumber *timestamp = response[1][#"LastMod"];

Resources