So I have an NSDictionary that has a variety of data within it. When printed to the log, it prints like this:
[{"user_id":3016817,"grade":"A","percent":"93","grading_periods":[{"assignments":[{"points":100.0,"grade":"A","score":95.0,"percent":"93","comment":null,"id":3268180},{"points":100.0,"grade":"A","score":90.0,"percent":"93","comment":null,"id":3268181}],"grade":"A","percent":"93","name":"Default"}]},{"user_id":3016818,"grade":"A","percent":"94","grading_periods":[{"assignments":[{"points":100.0,"grade":"A","score":92.0,"percent":"94","comment":null,"id":3268180},{"points":100.0,"grade":"A","score":95.0,"percent":"94","comment":null,"id":3268181}],"grade":"A","percent":"94","name":"Default"}]}]
If I use a formatter online, its a lot more readable and looks something like this:
[
{
"user_id": 3016817,
"grade": "A",
"percent": "93",
"grading_periods": [
{
"assignments": [
{
"points": 100,
"grade": "A",
"score": 95,
"percent": "93",
"comment": null,
"id": 3268180
},
{
"points": 100,
"grade": "A",
"score": 90,
"percent": "93",
"comment": null,
"id": 3268181
}
],
"grade": "A",
"percent": "93",
"name": "Default"
}
]
},
{
"user_id": 3016818,
"grade": "A",
"percent": "94",
"grading_periods": [
{
"assignments": [
{
"points": 100,
"grade": "A",
"score": 92,
"percent": "94",
"comment": null,
"id": 3268180
},
{
"points": 100,
"grade": "A",
"score": 95,
"percent": "94",
"comment": null,
"id": 3268181
}
],
"grade": "A",
"percent": "94",
"name": "Default"
}
]
}
]
My question would be how would I access the value of grade or score for a specific user_id using this dictionary?
Your string represents a NSArray, not a NSDictionary. And it's a JSON string, so you can parse it using NSJSONSerialization:
NSString *jsonString = #"..." // your string here
// Create array from json string
NSArray *jsonArray = [NSJSONSerialization
JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:Nil];
// Loop to find your user_id
// Because each child of this array is a dictionary
for (NSDictionary *dic in jsonArray) {
if ([dic[#"user_id"] isEqual:#3016817]) { // user_id field is number
// Access what you want
NSString *grade = dic[#"grade"];
// For "score" you must go deeper
// Just remember, [] is array and {} is dictionary
}
}
A simple way to do this would be
for (NSDictionary* d in theArray) {
if ([d[#"user_id"] isEqualToString: u]) {
// do something
}
}
And matt is right, it is an array of dictionaries, no matter what type you declared to be.
You can use below class method of NSJsonSerialization class to create NSArray which will contain all the dictionaries.
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
Once you get the array of dictionaries from JSON, you can do following:
NSArray *filteredjsonArr = [jsonArr filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"user_id == %#", #"3016818"]];
NSDictionary *dict = [filtered firstObject];
if (dict != nil) {
NSString *grade = [dict objectForKey:#"grade"];
NSArray *gradingPeriods = [dict objectForKey:#"grading_periods"];
}
To access score and grade for specific assignments, you'll need to drill down further into gradingPeriods array.
Related
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.
I am new to iOS and I want to parse data but it is so complex, I don't know how to parse it. Below given is the json data.
{
"response_code": 200,
"last_updated": {
"date": "2015-12-27",
"time": "01:32:13"
},
"trains": [
{
"train": {
"number": "04921",
"start_time": "04:45",
"name": "SRE-UMB MEMU SPECIAL",
"type": "HSP"
},
"dest": {
"code": "UMB",
"name": "AMBALA CANT JN"
},
"source": {
"code": "SRE",
"name": "SAHARANPUR"
}
},
{
"train": {
"number": "04922",
"start_time": "20:45",
"name": "UMB-SRE MEMU SPECIAL",
"type": "HSP"
},
"dest": {
"code": "SRE",
"name": "SAHARANPUR"
},
"source": {
"code": "UMB",
"name": "AMBALA CANT JN"
}
}
]
}
{ , , } - it's a dictionary
[ , , ] - it's an array
In your case you get:
First level - dictionary with keys response_code, last_updated, trains.
Where:
response_code - value
last_updated - dictionary with keys date, time
trains - array of dictionaries with keys train, dest, source
etc.
Use the NSJSONSerialization class, it's easy.
For example, in Objective-C:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonObject) {
// jsonObject is an NSArray or NSDictionary representation of the data that you can now do something with
}
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");
I've got a JSON Request that I'm able to add to an NSDictionary but I'm unable to access part of the JSON string. Here is a sample
{
"Resp": {
"Success": "True",
"who": {
"userid": 234,
},
"students": [
{
"ID": 1,
"name": John
},
{
"ID": 2,
"name": Jane
}
],
}
}
I am storing the data in an NSMutableDictionary and then passing that to my function which should run through each student and process them accordingly.
Here is what I've got so far and it's not working:
-(void)foo:(NSMutableDictionary*)json {
NSArray *students = json[#"students"];
for(NSMutableDictionary *student in students) {
NSLog(#"student id: %#", student[#"ID"]);
}
}
When debugging I can see the JSON object and students belongs under Resp as a value.
First of all, check your JSON on the validity http://jsonlint.com . It corrected your JSON with next modifications:
{
"Resp": {
"Success": "True",
"who": {
"userid": 234
},
"students": [
{
"ID": 1,
"name": "John"
},
{
"ID": 2,
"name": "Jane"
}
]
}
}
Then you should access your elements in right way:
- (void)foo:(NSMutableDictionary *)json {
NSArray *students = json[#"Resp"][#"students"];
for(NSDictionary *student in students) {
NSLog(#"student id: %#", student[#"ID"]);
}
}
For now it should be working.
That's the content...
[
{
"id": "",
"title": "",
"website": "",
"categories": [
{
"id": "",
"label": ""
}
],
"updated":
},
{
"id": "",
"title": "",
"website": "",
"categories": [
{
"id": "",
"label": ""
}
],
"updated":
}
]
How can I insert every feed source in one array?
NSDictionary *results = [string JSONValue];
NSArray *subs = [results valueForKey:#"KEY"];
Which key I must insert?
THanks
as I can see your structure, you will get out of this JSON-String
NSArray:
[
NSDictionary:
{
NSString: "id",
NSString: "title",
NSString: "website",
NSArray: "categories":
[
NSDictionary:
{
NSString: "id",
NSString: "label"
}
],
NSNumber: "updated"
},
NSDictionary:
{
...
}
]
So you have already an array of "Feeds" at root and you have to itterate them with their index in the array with. For first id i.e. [[myJsonStructure objectAtIndex:0] objectForKey:#"id"];