how to get array response from json in string? - ios

I am getting the response from json like this
parcel = (
{
datetime = "2015-08-31 21:48:45";
height = 2;
id = 21;
invoice = NO;
length = 2;
mtype = IN;
"num_item" = 2;
"parcel_number" = 1;
pname = "Parcel number - 1";
"pro_number" = tanu;
status = 1;
type = Exact;
uid = 185;
weight = 2;
width = 2;
wtype = KG;
}
);
I want to get the height,date time,invoice in a string.. How can this be done? AnyOne can help me for this...

NSArray * arr_Parcel = [[NSArray alloc]initWithArray:data];
NSMutableDictionary * temp_Dict = [[NSMutableDictionary alloc]init];
for (int i = 0 ; i < arr_Parcel.count; i++)
{
temp_Dict = [arr_Parcel objectAtIndex:i];
NSString * strHeight = [temp_Dict objectForKey:"height"];
NSString * strdate = [temp_Dict objectForKey:"datetime"];
}

If you are using Swift, use SwiftJSON to work with JSON.
It's easy to use. For example:
var jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let json = JSON(data: jsonData)
print(json["height"].double) // 2
print(json["datatime"].string) // "2015-08-31 21:48:45"
...

Create a NSObject Class and pass the NSDictionary the make a model class.
In your ViewController Class:
" parcel" is your Array
ModelClass * modelClass = [ModelClass alloc] initWithNewsDictionary: parcel[0]];
Create needed variables in ModelClass.h Class.
-(id)initWithNewsDictionary:(NSDictionary *)dictionary
{
self = [super init];
if (self) {
self.height = dictionary[#"height"];
self.datetime = dictionary[#"datetime"];
self.invoice = dictionary[#"invoice"];
self.weight = dictionary[#"weight"];
}
return self;
}

Try this :-
NSString *height=[NSString stringWithFormat:#"%#",[[[YourJson valueForKey:#"parcel"] objectAtIndex:0] objectForKey:#"height"]];
NSString *dateTime=[NSString stringWithFormat:#"%#",[[[YourJson valueForKey:#"parcel"] objectAtIndex:0] objectForKey:#"datetime"]];
NSString *invoice=[NSString stringWithFormat:#"%#",[[[YourJson valueForKey:#"parcel"] objectAtIndex:0] objectForKey:#"invoice"]];
NSLog(#"height : %# , date=%# ,invoice=%#",height,dateTime,invoice);

Related

How can I add in multiple items in model by using array method?

I have an original code as below which is working properly:-
- (ZYSideSlipFilterRegionModel *)commonFilterRegionModelWithKeyword:(NSString *)keyword selectionType:(CommonTableViewCellSelectionType)selectionType {
ZYSideSlipFilterRegionModel *model = [[ZYSideSlipFilterRegionModel alloc] init];
model.containerCellClass = #"SideSlipCommonTableViewCell";
model.regionTitle = keyword;
model.customDict = #{REGION_SELECTION_TYPE:#(selectionType)};
model.itemList = #[[self createItemModelWithTitle:[NSString stringWithFormat:#"Local"] itemId:#"0" selected:NO],
[self createItemModelWithTitle:[NSString stringWithFormat:#"Oversea"] itemId:#"1" selected:NO]];
return model;
}
Now, I plan to change the static value (Oversea / local) to dynamic value. But only 1 item will be displayed.
for (int i = 0; i < filteredArray.count; i++) {
int intItemID = i + 1;
NSString *myNewString = [NSString stringWithFormat:#"%i", intItemID];
model.itemList = #[[self createItemModelWithTitle:[filteredArray[i] valueForKey:#"attribute_name"] itemId:myNewString selected:NO] ];
}
How can I put 2 item in model.itemList? Please help. Thank you.
You can use this way
//step:1 fetch Dictionary like this
for (int i = 0; i < filteredArray.count; i++)
{
NSMutableDictionary *dict = (NSMutableDictionary *)filteredArray[i] ;
int intItemID = i + 1;
NSString *myNewString = [NSString stringWithFormat:#"%i", intItemID];
model.itemList = #[[self createItemModelWithTitle:dict];
}
//Step 2 : You can define your method for Model Like this
- (CommonItemModel *)createItemModelWithTitle:(NSMutableDictionary *)dictModel
{
CommonItemModel *model = [[CommonItemModel alloc] init];
model.itemId = [dictModel valueForKey : #"itemId"];
model.itemName = [dictModel valueForKey:#"itemTitle"];
model.selected = [dictModel valueForKey:[NSNumber numberWithBool:
[[dictModel valueForKey:#"selected"]]]];
return model;
}
//One more thing you are write this in first step
model.itemList = #[[self createItemModelWithTitle:dict];
But the method only return the Model class (CommonItemModel) so if you need any help you shared here
Thanks :)

Q - iOS - Search and use specific part of parsed JSON array

This is my first time using JSON. In my app I am fetching some data from "Open Weather API". I get back some array, with way to many entries, and I need to search ones that are on specific day and return temp.day and weather.icon from them. So far I managed to fetch data propely. As far I know i should use some FOR loop with IF inside it, but I am pulling my hairs out how to do it in Objective C.
There is my fetch method:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* weatherList = [json objectForKey:#"list"];
NSLog(#"everything %#", weatherList ); //3
}
And part array from NSLog:
{
clouds = 92;
deg = 265;
dt = 1456221600;
humidity = 100;
pressure = "1007.96";
rain = "0.24";
speed = "5.12";
temp = {
day = "4.11";
eve = "4.62";
max = "4.87";
min = "2.78";
morn = "4.11";
night = "2.78";
};
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
},
{
clouds = 88;
deg = 268;
dt = 1456308000;
humidity = 98;
pressure = "1012.04";
rain = "1.31";
speed = "6.35";
temp = {
day = "3.57";
eve = "3.74";
max = "3.74";
min = "2.38";
morn = "2.53";
night = "2.38";
};
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
},
{
clouds = 20;
deg = 243;
dt = 1456394400;
humidity = 100;
pressure = "1015.42";
snow = "0.25";
speed = "5.08";
temp = {
day = "2.95";
eve = "4.09";
max = "4.54";
min = "-0.65";
morn = "1.74";
night = "-0.65";
};
weather = (
{
description = "light snow";
icon = 13d;
id = 600;
main = Snow;
}
);
},
{
clouds = 80;
deg = 273;
dt = 1456480800;
humidity = 100;
pressure = "1016.63";
snow = "0.04";
speed = "2.79";
temp = {
day = "0.2";
eve = "2.79";
max = "2.79";
min = "-3.33";
morn = "-2.7";
night = "-2.42";
};
weather = (
{
description = "light snow";
icon = 13d;
id = 600;
main = Snow;
}
);
},
{
clouds = 87;
deg = 132;
dt = 1456567200;
humidity = 0;
pressure = "1007.07";
rain = "0.22";
snow = "0.03";
speed = 5;
temp = {
day = "3.96";
eve = "1.48";
max = "3.96";
min = "-3.12";
morn = "-3.12";
night = "-1.59";
};
weather = (
{
description = "clear sky";
icon = 01d;
id = 800;
main = Clear;
}
);
}
What are good practices? Do I fetch proper enough big part of JSON?
Should I use dome NSDictionary too? Any ideas are welcome!
Thanks
1) As per documentation given the time is in GMT format so you need to convert the time in IST to compare
here is code to convert the time . I dont know your time zone I converted it in Indian Standard Time
for ( NSDictionary *obj in weatherList) {
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = #"dd-MM-yyyy";
inDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"IST"];
NSDate *inDate = [inDateFormatter dateFromString:[obj objectForKey:#"dt"]];
if ([self isItToday:inDate]) {
NSDictionary * tempDict = [obj objectForKey:#"temp"];
NSDictionary * weatherDict = [[obj objectForKey:#"weather"]objectForKey:0];
NSString * dayTemp = [tempDict objectForKey:#"day"];//only storing for time being you can use where you needed
NSString * icon = [weatherDict objectForKey:#"icon"];//only storing for time being you can use where you needed
}
}
2) Now you need to compare it with todays date
+ (BOOL)isItToday:(NSDate *)date {
if (date != nil) {
NSString *givenDateString = [self stringFromDate:date inDateFormat:#"dd-MM-yyyy"];
NSString *toDayString = [self stringFromDate:[NSDate date] inDateFormat:#"dd-MM-yyyy"];
NSDate *givenDate = [self dateFromString:givenDateString inDateFormat:#"dd-MM-yyyy"];
NSDate *toDay = [self dateFromString:toDayString inDateFormat:#"dd-MM-yyyy"];
if ([givenDate isEqualToDate:toDay]) {
return YES;
} else {
return NO;
}
} else {
return NO;
}
}
+ (NSString *)stringFromDate:(NSDate *)date inDateFormat:(NSString *)inDateformat
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:kLocaleIdentifierEN_US_POSIX];
[dateFormatter setDateFormat:inDateformat];//#"dd/MM/yyyy"
return [dateFormatter stringFromDate:date];
}
+ (NSDate *)dateFromString:(NSString *)stringDate inDateFormat:(NSString *)inDateformat
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:kLocaleIdentifierEN_US_POSIX];
[dateFormatter setDateFormat:inDateformat];//#"dd/MM/yyyy"
return [dateFormatter dateFromString:stringDate];
}
also add this line
#define kLocaleIdentifierEN_US_POSIX [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]
Use following code,
double comparingdt = 1456308000;
__block NSString *tempday, *weathericon;
[weatherList enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSDictionary *weather, NSUInteger idx, BOOL * _Nonnull stop) {
*stop = ([weather[#"dt"] doubleValue] == comparingdt);
if (*stop)
{
tempday = weather[#"temp"][#"day"];
weathericon = [weather[#"weather"] firstObject][#"icon"];
}
}];

How to merge 2 NSDictionaries in NSMutableArray having same value in iOS?

I have an NSMutableArray with NSDictionaries like below format
(
{
"login_id" = 95;
consDays = "Mon,Tue";
consEndTime = 12600000;
consStartTime = 9000000;
duration = 10;
id = 58;
isActive = 1;
},
{
"login_id" = 95;
consDays = "Wed,Thur";
consEndTime = 41400000;
consStartTime = 23400000;
duration = 10;
id = 59;
isActive = 1;
},
{
"login_id" = 98;
consDays = "Mon,Tue,Wed,Thur,Fri,Sat,Sun";
consEndTime = 45000000;
consStartTime = 9000000;
duration = 30;
id = 60;
isActive = 1;
},
I can see here first 2 object's with "login_id" 95 are same and i need to merge the contents and make something like this one
{
"login_id" = 95;
consDays = "Mon,Tue-Wed,Thur";
consEndTime = 12600000-41400000;
consStartTime = 9000000-23400000;
duration = 10;
id = 58;
isActive = 1;
},
i have tried with for loop and its not getting clear
for(int i=0;i<[[arr valueForKey:#"data"] count];i++){
NSString *bloginId=[NSString stringWithFormat:#"%#",[[[arr valueForKey:#"data"] valueForKey:#"branchLogin_id"] objectAtIndex:i]];
for(int j=0;j<[[arr valueForKey:#"data"] count];j++){
NSString *firstId=[NSString stringWithFormat:#"%#",[[[arr valueForKey:#"data"] valueForKey:#"branchLogin_id"] objectAtIndex:i]];
NSString *secondId=[NSString stringWithFormat:#"%#",[[[arr valueForKey:#"data"] valueForKey:#"branchLogin_id"] objectAtIndex:j]];
NSLog(#"%#-%#",firstId,secondId);
if([firstId isEqualToString:secondId]){
NSLog(#"%#",[consultationDetailsArray valueForKey:#"branchLogin_id"]);
if([[consultationDetailsArray valueForKey:#"branchLogin_id"] containsObject:secondId]){
NSString *str=[NSString stringWithFormat:#"%#,%#",[[consultationDetailsArray valueForKey:#"consDays"] objectAtIndex:j],[[[arr valueForKey:#"data"] valueForKey:#"consDays"] objectAtIndex:j]];
NSLog(#"consDays %#",str);
}else{
[consultationDetailsArray addObject:[[arr valueForKey:#"data"] objectAtIndex:j]];
}
}
}
}
can anyone help me ?
Ironically I am doing just this same thing right now. Looks like the easiest way is to use a NSMutableDictionary.
// Assume two starting dictionaries.
dictionaryOne;
dictionaryTwo;
//
// Create a mutable copy of the first
NSMutableDictionary *merged = dictionaryOne.mutableCopy;
[merged addEntriesFromDictionary: dictionaryTwo];
//
// merged now contains all keys of both dictionaries
// keys that are in both dictionaries will have values
// from dictionaryTwo.
Hope this helps.

Adding Multiple NSArrays to NSMutableDictionary with corresponding matching item in array order

I have two arrays say itemName and itemImages
NSArray *itemName = #[#"Blog", #"Missions", #"Subscriptions", #"Questions", #"Aide",#"Disconnect"];
NSArray *itemImages = #[#"ico-1",#"ico-2", #"ico-3", #"ico-4", #"ico-5", #"ico-6"];
I need to add them to a dictionary
NSMutableDictionary *menuItemNameImage = [[NSMutableDictionary alloc] init];
[menuItemNameImage setValue:itemName forKey:#"itemName"];
[menuItemNameImage setValue:itemImages forKey:#"itemImages"];
NSLog(#"%#", menuItemNameImage);
But this makes the following Dictionary
{
itemImages = (
"ico-1",
"ico-2",
"ico-3",
"ico-4",
"ico-5",
"ico-6"
);
itemName = (
Blog,
Missions,
Subscriptions,
Questions,
Aide,
Disconnect
);
}
What I rather want is some think like this :
{
{
itemImages = "icon-1",
itemName = Blog
},
{
itemImage = "icon-2",
itemName = "Missions"
}, ...
}
You cannot get that structure with a single NSDictionary - you need an NSArray of NSDictionary objects.
Here is how you can do it:
NSMutableArray *menuItemNameImage = [NSMutableArray array];
for (int i = 0 ; i != itemNames.count ; i++) {
[menuItemNameImage addObject: #{
#"itemName" : itemNames[i]
, #"itemImage" : itemImages[i]
}];
}
What you could use is a NSArray of NSDictionaries. Each dictionary would have two entries: an itemImage and itemName.
It would be something like this:
NSArray *itemName = #[#"Blog", #"Missions", #"Subscriptions", #"Questions", #"Aide",#"Disconnect"];
NSArray *itemImages = #[#"ico-1",#"ico-2", #"ico-3", #"ico-4", #"ico-5", #"ico-6"];
NSMutableArray *menuItemNameImage = [NSMutableArray new];
for (NSInteger i = 0; i < itemName.count; i++) {
NSMutableDictionary *itemNameImage = [NSMutableDictionary new];
itemNameImage[#"itemName"] = itemName[i];
//just a precaution if the array os images is smaller than the ones of names, to avoid unwanted crashes
if (i < itemImages.count) {
itemNameImage[#"itemImage"] = itemImages[i];
}
[menuItemNameImage addObject:itemNameImage];
}
NSLog(#"%#", menuItemNameImage);
The output, as you want:
(
{
itemImage = "ico-1";
itemName = Blog;
},
{
itemImage = "ico-2";
itemName = Missions;
},
{
itemImage = "ico-3";
itemName = Subscriptions;
},
{
itemImage = "ico-4";
itemName = Questions;
},
{
itemImage = "ico-5";
itemName = Aide;
},
{
itemImage = "ico-6";
itemName = Disconnect;
}
)
You can access the elements like this, for example:
NSString *firstItemName = menuItemNameImage[0][#"itemName"];
NSString *firstItemImage = menuItemNameImage[0][#"itemImage"];

Accessing the xml values from NSDictionary

I am using this xmlreader. Here is my code
NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:&error1];
NSLog(#"XMLData: %#",xmlDict);
I can save and log the data and it looks like this.
response = {
Gpn0 = {
text = 10000;
};
Gsn0 = {
text = 4;
};
btn0 = {
text = up;
};
};
}
But how can I access a single element from this dictionary?
NSDictionary *gpn0 = response[#"Gpn0"];
NSNumber *gpn0_text = gpno[#"text"]; // note this is a numeric value
NSDictionary *btn0 = response[#"btn0"];
NSString *btn0_text = gpno[#"text"]; // note this is a string value
so on and so forth

Resources