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");
Related
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);
}}
Here's the response:
{
"status": true,
"statuscode": 200,
"result": [
{
"name": "ABC",
"date": "2015-01-30",
"documents": [
{
"id": 1,
"name": "doc1",
"status": "complete",
},
{
"id": 2,
"name": "doc2",
"status": "complete",
},
{
"id": 3,
"name": "doc3",
"status": "complete",
}
],
"message": "Hello World",
"status": 3
}
]
}
I want to map and get only all the "document" inside an array keyed "result" and I don't need anything with other objects / mappings. I just need the documents. How can that be done / declared in the response descriptors to automatically match all these documents to my managed object?
Try This :-
NSDictionary *dic=#{
#"status": #true,
#"statuscode":# 200,
#"result": #[
#{
#"name": #"ABC",
#"date": #"2015-01-30",
#"documents": #[
#{
#"id":# 1,
#"name": #"doc1",
#"status": #"complete",
},
#{
#"id":# 2,
#"name": #"doc2",
#"status":# "complete",
},
#{
#"id":# 3,
#"name": #"doc3",
#"status": #"complete",
}
],
#"message": #"Hello World",
#"status":# 3
}
]
};
I am storing your response in NSDictionary and get it by -
[[[dic objectForKey:#"result"] objectAtIndex:0] objectForKey:#"documents"]
change your indexNumber as require !
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; //From Server you will get response data in form of NSData , so the 'responseData' is a type of NSData
NSArray *appDetais = [jsonData objectForKey:#"result"];
NSDictionary *resultJsonData = [appDetais objectAtIndex:0];
NSArray *documentDetailsArray = [jsonData resultJsonData:#"documents"];
for(int i=0;i<[documentDetailsArray count];i++){
NSDictionary *singleDocumentDetail = [documentDetailsArray objectAtIndex:0];
NSLog(#"%#",[singleDocumentDetail objectForKey:#"id"]);
}
You may try this.. :)
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) {
...
}
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.
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"];