webservice response dictionary disable auto sorted by keys? - ios

I am facing issue with my webserice response. Dictionary keys are auto sorted and i want them as it is
the actual webservice response is :-
[data] => Array
(
[18] => How it works
[22] => Benefits
[23] => Win Free Airtime
[7] => What can I Report?
[10] => Our Goal
[16] => Disclaimer
[8] => FAQ
[13] => Terms & Conditions
[11] => Contact Us
[14] => Feedback / suggestion
)
and it is showing below unfortunately by auto sorting
data = {
10 = "Our Goal";
11 = "Contact Us";
13 = "Terms & Conditions";
14 = "Feedback / suggestion";
16 = Disclaimer;
18 = "How it works";
22 = Benefits;
23 = "Win Free Airtime";
7 = "What can I Report?";
8 = FAQ;
};
I am stuck :( below is my code
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[spinner stopAnimating];
if ([data length] > 0 && error == nil)
{
//NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary * Dict = [NSDictionary dictionary];
NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *decryptedStr = [[NSData alloc] initWithBase64EncodedString:newStr options:0];
NSDictionary * Dict = [NSJSONSerialization JSONObjectWithData:decryptedStr options:kNilOptions error:nil];

There is no way to do this, because the result is not an array but a dictionary which does not have an order.
You will have to write your own JSON parser and use something else than an NSDictionary to keep the order.
The best way is to change the JSON output use an array:
{
"data": [
{
"key": 10,
"value": "Our Goal"
},
{
"key": 11,
"value": "Contact Us"
},
{
"key": 13,
"value": "Terms & Conditions"
},
{
"key": 14,
"value": "Feedback / suggestion"
},
{
"key": 16,
"value": "Disclaimer"
},
{
"key": 18,
"value": "How it works"
},
{
"key": 22,
"value": "Benefits"
},
{
"key": 23,
"value": "Win Free Airtime"
},
{
"key": 7,
"value": "What can I Report?"
},
{
"key": 8,
"value": "FAQ"
}
]
}

Related

IOS JSON Parsing Containing Multiple Arrays

I have a JSON array with multiple object and I don't know how do I grab the "url" tag as an NSArray or a NSDictionary and show that image url in CollectionView. I can't change the JSON data format.How should I do this?
Here is what the JSON response looks like:
{
"error": false,
"data": [
{
"albumid": 2,
"albumtitle": "Album 2",
"images": [
{
"image": "Img2.jpeg",
"imageid": 11
},
{
"image": "vr4.jpg",
"imageid": 4
},
{
"image": "3purple b-ball.jpg",
"imageid": 3
}
]
},
{
"albumid": 3,
"albumtitle": "Album 3",
"images": [
{
"image": "vr2.jpg",
"imageid": 6
},
{
"image": "vr1.jpg",
"imageid": 5
}
]
},
{
"albumid": 4,
"albumtitle": "Album 4",
"images": [
{
"image": "vr1.jpg",
"imageid": 8
}
]
},
{
"albumid": 12,
"albumtitle": "My Album",
"images": [
{
"image": "img3.jpeg",
"imageid": 64
},
{
"image": "img4.jpeg",
"imageid": 63
},
{
"image": "img5.jpeg",
"imageid": 62
}
]
},
{
"albumid": 13,
"albumtitle": "Demo Album",
"images": [
{
"image": "img6.jpeg",
"imageid": 67
},
{
"image": "img7.jpeg",
"imageid": 66
},
{
"image": "img11.jpeg",
"imageid": 65
}
]
}
]
}
Try something like this (data is the NSData object you get from your webserver):
NSError *jsonError = nil;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if(!jsonError){
NSArray *dataArray = [jsonData objectForKey:#"data"];
NSDictionary *albumDict = [dataArray objectAtIndex:0];
NSArray *imagesArray = [albumDict objectForKey:#"images"];
NSDictionary *imageDict = [imagesArray objectAtIndex:0];
NSString *imageURL = [imageDict objectForKey: #"image"];
}
Of course, you have to use loops for the array elements, this example is only with element 0. Some more checks if a field exists etc. would be good.
You can create a model to hold the image id and url. You add an array of these image objects in the main model (Album). In Swift, your models might look like this
class Album {
var albumId = ""
var albumTitle = ""
var albumImages = [AlbumImage]()
}
class AlbumImage {
var imageId = ""
var imageUrl = ""
}
Hope this helps!
Use this code after downloaded the json file.
NSDictionary *rootDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *rootArray = rootDict[#"data"];
NSDictionary *subDict;
NSArray *subArray;
NSDictionary *tempDict;
for (int i=0; i<rootArray.count; i++) {
subDict = rootArray[i];
subArray = subDict[#"images"];
for (int j=0; j<subArray.count; j++) {
tempDict = subArray[j];
NSLog(#"%#",tempDict[#"image"]);
}
}
in JSONObjectSerialization data was NSData object where the json file downloaded.

how to fetch data using json parsing in ios and show result in another page?

I want to take data from one of website which will be in json format and want to show it in second page of my app. How can i parse it in ios?
json response is going to e like this :
{
"response_code": 200,
"error": false,
"train_name": "KCG YPR EXP",
"train_num": "17603",
"pnr": "1234567890",
"failure_rate": 19.346153846153847,
"doj": "20-8-2015",
"chart_prepared": "Y",
"class": "SL",
"total_passengers": 2,
"train_start_date": {
"month": 8,
"year": 2015,
"day": 20
},
"from_station": {
"code": "KCG",
"name": "KACHEGUDA"
},
"boarding_point": {
"code": "KCG",
"name": "KACHEGUDA"
},
"to_station": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"reservation_upto": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"passengers": [
{
"no": 1,
"booking_status": "S7,58,GN",
"current_status": "S7,58",
"coach_position": 9
},
{
"no": 2,
"booking_status": "S7,59,GN",
"current_status": "S7,59",
"coach_position": 9
}
]
}
NSError *err;
NSURL *url=[NSURL URLWithString:#"your url"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&err];
NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

Nested NSDictionary from JSON in Xcode

Hi I been having huge issues grabbing some data out of this for me quite complex JSON structure.
The problem is that the JSON structure contains some nesting that i can't find out how to handle.
Example of the JSON i get from the database:
{
"hits": {
"totalHits": 3202,
"hits": [{
"id": "70132eb7-2834-458c-900a-da951c95a506",
"versions": [{
"id": 7,
"properties": {
"Status": [
"usable"
],
"created": [
"2015-10-27T14:31:13Z"
],
"Text": [
"Snabbtåg, Järnväg, Höghastighetsjärnväg, "
],
"ConceptDefinitionLong": [
"Enligt Trafikverket saknas en helt entydig och vedertagen definition av höghastigheteståg."
],
"contenttype": [
"Concept"
],
"ConceptProposalUser": [
"[object Object]"
],
"ConceptType": [
"object"
],
"Name": [
"Höghastighetståg"
],
"ConceptNote": null,
"ConceptSeeAlso": null,
"Note": null,
"ConceptName": [
"Höghastighetståg"
],
"updated": [
"2016-02-01T11:37:30Z"
],
"ConceptDefinitionShort": [
"Snabbtåg, Järnväg, Höghastighetsjärnväg, Kollektivtrafik"
],
"ConceptStatus": [
"usable"
]
}
}],
"noVersions": 1
}, {
"id": "4224ccfb-1f0a-9491-727f-f6ab0fc2c951",
"versions": [{
"id": 2,
"properties": {
"Status": [
"usable"
],
"created": [
"2016-01-25T12:03:33Z"
],
"Text": [
"Rosenlundsbadet öppnade 1968 och äventyrsbadet 1991."
],
"ConceptDefinitionLong": [
"Rosenlundsbadet är en badanläggning i Jönköping. "
],
"contenttype": [
"Concept"
],
"ConceptProposalUser": null,
"ConceptType": [
"organisation"
],
"Name": [
"Rosenlundsbadet"
],
"ConceptNote": null,
"ConceptSeeAlso": null,
"Note": null,
"ConceptName": [
"Rosenlundsbadet"
],
"updated": [
"2016-01-25T12:03:38Z"
],
"ConceptDefinitionShort": [
"Simning, Simhopp, Äventyrsbad"
],
"ConceptStatus": [
"usable"
]
}
}],
"noVersions": 1
}
...
My job is to get all the "Name"s from all posts where the "Status" is set to "usable". And store them in my app. But I'm having a hard time getting that info . Im new to JSON and can't handle the structure. This is what i got so far after hours of googling:
NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.pumba.se/example.json"]];
NSError *error;
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
NSDictionary *firstItem = [entries objectAtIndex:0];
NSString *id1 = [firstItem objectForKey:#"id"];
NSLog(#"ID: ");
NSLog(id1);
}}
From that code I'm able to get the ID from the first item. But I don't seem to be able to fetch the "name" or check if they are "usable". Have been working with this and trying to solve this for hours but this is above my leauge. I guess the reason to why I can't solve it is cause the data is nested in hits.hits etc. Yet I have to solve this to be able to finish my app. I would be very grateful for some help.
Here is a longer version of the JSON database. The full version contains over 3000 items:
http://jsonviewer.stack.hu/#http://www.pumba.se/example.json
You can use the following code:
NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://www.pumba.se/example.json"]];
NSError *error;
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}

IOS Complex JSON Structure Parsing

I Want to parse complex JSON structure JSON is given Below USING IOS.
What lib should i use, or any other lib`s custom available
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address":
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber":
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
Read the JSON data into an NSData object, and use NSJSONSerialization's JSONObjectWithData:options:error: method. The result will be an NSDictionary containing NSString, NSDictionary, and NSArray objects.
So for example:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"file:///myfile.txt"]]; // Probably get this from somewhere else, but you get the idea.
NSError *error = nil;
id topObject = [NSJSONSerialization JSONObjectWithData:data options:0 error: &error];
if ([topObject isKindOfClass:[NSDictionary class]] && !error) {
...
}

Parsing a response from JSON , ios?

I have the below parameter in my json.
{
"msg": "success",
"data": [
{
"FNAME": "test",
"LNAME": null,
"STATUS": null,
"MOBILE1": "1234567890",
"show_email": "1",
"Info": [
{
"id": "73307",
"NAME": "demo",
"CONTACT": "",
"WORKING_HOUR1": "[\"09:00 AM\",\"09:15 AM\",\"09:30 AM\",\"09:45 AM\",\"10:00 AM\"]",
"WORKING_HOUR7": "",
"DAY": "[\"Monday\",\"Wednesday\"]"
}
]
}
]
}
I am not able to understand how do I get values from it.
If I parse this I get the error
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *results = [res objectForKey:#"data"];
NSArray *Info=[results[0] objectForKey:#"Info"];
NSArray *day=clinicInfo[1][#"DAY"];
NSLog(#"%#", day[0]);
Error:
'NSInvalidArgumentException', reason: '-[__NSCFString objectAtIndexedSubscript:
EDIT:
From your JSON you want:
NSArray *days = json[#"data"][0][#"Info"][0][#"DAY"]
Also while your JSON is valid, the days and working hours are not in an array - they are a string.
You need something like this.
{
"msg": "success",
"data": [
{
"FNAME": "test",
"LNAME": null,
"STATUS": null,
"MOBILE1": "1234567890",
"show_email": "1",
"Info": [
{
"id": "73307",
"NAME": "demo",
"CONTACT": "",
"WORKING_HOUR1": [
"09:00 AM",
"09:15 AM",
"09:30 AM",
"09:45 AM",
"10:00 AM"
],
"WORKING_HOUR7": "",
"DAY": [
"Monday",
"Wednesday"
]
}
]
}
]
}
Firstly you are not using valid JSON.
{
"DAY": [
"Monday",
"Wednesday"
]
}
You can use NSJSONSerialization to parse the JSON file, from which you should get a NSDictionary.
In that dictionary there should be a NSArray for the key "DAY", which contains 2 objects both strings, "Tuesday" and "Thursday".
eg. Where data is your JSON file
NSError *jsonError = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if(!jsonError) NSArray *days = json[#"DAY"];
else NSLog(#"Error serialising JSON");

Resources