Problems with parsing JSON feed in app - iphone

The following JSON feed contains orders.
How can I retrieve each order, when it doesn't contain a key (canĀ“t use objectForKey)? Between the opening bracket and the first curly bracket there is no key.
[ <-----
{ <-----
"person": {
"address": "My road",
"city": "My City",
"name": "My Name",
},
"orderDate": "30.05.2012 10:27",
"orderId": 10001,
"orderlines": [
{
"unit": {
"unitId": "RA005",
"name": "My Unit name",
},
"id": 10007,
"deliveryInfo": {
"count": 1,
"date": "30.05.2012",
"format": "MY_FORMAT",
},
"sum": 0,
"details": "Testing",
"priority": 3,
}
],
"received": true,
"status": "REGISTERED",
"sumPrice": 0
},
{
"person": {
"address": "My road 2",
"city": "My City 2",
"name": "My Name 2",
},
"orderDate": "30.04.2012 10:27",
"orderId": 10002,
"orderlines": [
{
"unit": {
"unitId": "RA006",
"name": "My Unit name 2",
},
"id": 10008,
"deliveryInfo": {
"count": 2,
"date": "01.06.2012",
"format": "MY_FORMAT",
},
"sum": 0,
"details": "Testing",
"priority": 2,
}
],
"received": true,
"status": "REGISTERED",
"sumPrice": 0
}
]

whenever you see [] (square brackets), it represents array. so use object at index to return the at indexes. one approach is to pass the object into array like
NSMutableArray *arr = (NSMutableArray*) jsonData;

since the root of your json is an array,
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}

Related

Retrieve only matched object from nested array in mongodb

In this json , I need a find query which finds all the field where the "status":"Y", if the parent field has "status":"N", ignore the child field , else find the child field where the "status":"Y" along with its parent field
Note: The sub field is in a array
[
{
"type": "Type 1",
"status": "Y",
"code": "1",
"category": [
{
"type": "Cat 1",
"status": "Y",
"code": "1000",
"subcategories": [
{
"type": "Sub 1",
"status": "N",
"code": "1001"
},
{
"type": "Sub 2",
"status": "N",
"code": "1002"
},
{
"type": "Sub 3",
"status": "Y",
"code": "1003"
}
]
},
{
"type": "Cat 2",
"status": "N",
"code": "2000",
"subcategories": [
{
"type": "Sub 4",
"status": "Y",
"code": "2001"
},
{
"type": "Sub 5",
"status": "Y",
"code": "2002"
}
]
}
]
}
]
My Output Should be like this
[
{
"type": "Type 1",
"status": "Y",
"code": "1",
"category": [
{
"type": "Cat 1",
"status": "Y",
"code": "1000",
"subcategories": [
{
"type": "Sub 3",
"status": "Y",
"code": "1003"
}
]
} ]
}
]
Thanks in Advance:)
You can try below aggregation
db.collection.aggregate([
{ "$match": { "status": "Y" }},
{ "$unwind": "$category" },
{ "$match": { "category.status": "Y" } },
{ "$project": { "type": 1, "status": 1, "code": 1,
"category.type": "$category.type",
"category.status": "$category.status",
"category.code": "$category.code",
"category.subcategories": {
"$filter": {
"input": "$category.subcategories",
"as": "subcategory",
"cond": {
"$eq": [
"$$subcategory.status",
"Y"
]
}
}
}
}},
{ "$group": {
"_id": "$_id",
"type": { "$first": "$type" },
"status": { "$first": "$status" },
"code": { "$first": "$code" },
"category": { "$push": "$category" }
}}
]).then((data) => {
res.send(data)
})
Gives you following output (check here)
[
{
"_id": ObjectId("5a934e000102030405000000"),
"category": [
{
"code": "1000",
"status": "Y",
"subcategories": [
{
"code": "1003",
"status": "Y",
"type": "Sub 3"
}
],
"type": "Cat 1"
}
],
"code": "1",
"status": "Y",
"type": "Type 1"
}
]

How to parse json ki typical format in iphone

I am trying to parse json. but not able to get correct key. I am using JSONKIT. Below is the json data.SO i am trying to get CONTENT pls help me how to do this.
`{
"apiVersion": "2.1",
"data": {
"updated": "2013-06-13T06:15:22.613Z",
"totalItems": 1000000,
"startIndex": 1,
"itemsPerPage": 25,
"items": [
{
"id": "l2h9kFq3TFQ",
"uploaded": "2013-04-09T15:20:46.000Z",
"updated": "2013-06-11T22:32:56.000Z",
"uploader": "trollinforlaughs",
"category": "Games",
"title": "Funny Fail Compilation 2013",
"description": "by FAIL.nl LOOKING FOR YOUTUBE PARTNERSHIP? http://www.acifinnetwork.com/a/bigshotz \"Extra Tags: \"girls fail compilation\" \"fail compilation 2012\" \"compilatio...",
"thumbnail": {
"sqDefault": "https://i.ytimg.com/vi/l2h9kFq3TFQ/default.jpg",
"hqDefault": "https://i.ytimg.com/vi/l2h9kFq3TFQ/hqdefault.jpg"
},
"player": {
"default": "https://www.youtube.com/watch?v=l2h9kFq3TFQ&feature=youtube_gdata_player",
"mobile": "https://m.youtube.com/details?v=l2h9kFq3TFQ"
},
"content": {
"1": "rtsp://v8.cache7.c.youtube.com/CiILENy73wIaGQlUTLdakH1olxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
"5": "https://www.youtube.com/v/l2h9kFq3TFQ?version=3&f=videos&app=youtube_gdata",
"6": "rtsp://v8.cache7.c.youtube.com/CiILENy73wIaGQlUTLdakH1olxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
},
"duration": 776,
"aspectRatio": "widescreen",
"rating": 4.463792,
"likeCount": "13094",
"ratingCount": 15121,
"viewCount": 6493167,
"favoriteCount": 0,
"commentCount": 5316,
"accessControl": {
"comment": "allowed",
"commentVote": "allowed",
"videoRespond": "moderated",
"rate": "allowed",
"embed": "allowed",
"list": "allowed",
"autoPlay": "allowed",
"syndicate": "allowed"
}
},
{
"id": "DfznjFrNvf4",
"uploaded": "2013-05-24T19:15:36.000Z",
"updated": "2013-06-10T01:11:01.000Z",
"uploader": "funnymediatv",
"category": "Comedy",
"title": "The Ultimate Fail,Win and Funny pranks Mega Compilation part 96",
"description": "Rate, Share and Subscribe ! Like us on Facebook: https://www.facebook.com/BestFunnyFails Funny Fails Community: https://plus.google.com/u/0/communities/11109...",
"thumbnail": {
"sqDefault": "https://i.ytimg.com/vi/DfznjFrNvf4/default.jpg",
"hqDefault": "https://i.ytimg.com/vi/DfznjFrNvf4/hqdefault.jpg"
},
"player": {
"default": "https://www.youtube.com/watch?v=DfznjFrNvf4&feature=youtube_gdata_player",
"mobile": "https://m.youtube.com/details?v=DfznjFrNvf4"
},
"content": {
"1": "rtsp://v6.cache2.c.youtube.com/CiILENy73wIaGQn-vc1ajOf8DRMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
"5": "https://www.youtube.com/v/DfznjFrNvf4?version=3&f=videos&app=youtube_gdata",
"6": "rtsp://v6.cache2.c.youtube.com/CiILENy73wIaGQn-vc1ajOf8DRMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
},
"duration": 619,
"aspectRatio": "widescreen",
"rating": 4.6666665,
"likeCount": "220",
"ratingCount": 240,
"viewCount": 55915,
"favoriteCount": 0,
"commentCount": 28,
"accessControl": {
"comment": "allowed",
"commentVote": "allowed",
"videoRespond": "moderated",
"rate": "allowed",
"embed": "allowed",
"list": "allowed",
"autoPlay": "allowed",
"syndicate": "allowed"
}
}
]
}
}`
SO i am trying to get CONTENT pls help me how to do this.
Sample Code :
NSDictionary *content = [[[[yourJSONResponseDict objectForKey:#"data"] objectForKey:#"items"] objectAtIndex:0] objectForKey:#"content"];
NSLog(#"Content :: %#",content);
Explanation :
//1. This will give you the "Value" for key "data".
NSDictionary *data = [yourJSONResponseDict objectForKey:#"data"];
//2. This will give you the "Value" for key "items" which is inside "data" Dictionary.
NSArray *items = [data objectForKey:#"items"];
//3. This will give you the First Object of "items" Array which is a Dictionary.
NSDictionary *itemObject = [items objectAtIndex:0];
//4. This will give you your Final Component named "Content" which is a Dictionary also.
NSArray *content = [itemObject objectForKey:#"content"];

Json parsing wrong in IOS

Hi i have some problem parsing the json in IOS. This is the json data.
{
"app_info": [
{
"app_name": "haka",
"sync_protocol_version": "1"
}
],
"updates": [
{
"timestamp": "Sat Apr 21 13:04:08 IST 2012",
"people": [
{
"personal_info": [
{
"first_name": "phlox",
"last_name": "",
"employee_id": "010",
"gender": "-",
"marital_status": "-",
"nationality": "Denobulan",
"dob": "re-23",
"photo": "http://c.cc/users/010/profile/image"
}
],
"contact_details": [
{
"address": [
{
"street": "#1, this way",
"city": "tank",
"state": "sick bay",
"zip": "0978",
"country": "Enterprise"
}
],
"telephone": [
{
"work": "010",
"mobile": "010",
"home": "010"
}
],
"email": [
{
"work": "phlox#nx-10.ent",
"personal": ""
}
]
}
],
"emergency": [
{
"contact": [
{
"name": "-",
"relationship": "",
"telephone": [
{
"work": "",
"home": "",
"mobile": ""
}
]
}
],
"blood_group": ""
}
],
"categorization": [
{
"designation": "",
"department": "",
"location": "",
"joining_date": ""
}
]
},
{
"personal_info": [
{
"first_name": "",
"last_name": "",
"employee_id": "",
"gender": "",
"marital_status": "",
"nationality": "",
"dob": "",
"photo": ""
}
],
"contact_details": [
{
"address": [
{
"street": "",
"city": "",
"state": "",
"zip": "",
"country": ""
}
],
"telephone": [
{
"work": "",
"mobile": "",
"home": ""
}
],
"email": [
{
"work": "",
"personal": ""
}
]
}
],
"emergency": [
{
"contact": [
{
"name": "",
"relationship": "",
"telephone": [
{
"work": "",
"home": "",
"mobile": ""
}
]
}
],
"blood_group": ""
}
],
"categorization": [
{
"designation": "",
"department": "",
"location": "",
"joining_date": ""
}
]
}
],
"messages": [
{
"sender": "Archer<admin#nx-10.ent>",
"sender_role": "admin",
"message_type": "broadcast",
"message": "parking space up for grabs",
"message_recipients": "all",
"reply_permitted": "0"
}
],
"events": [
{
"creator": "Travis<ensign#nx-01.ent>",
"event_title": "",
"event_description": "",
"event_time_start": "",
"event_time_end": "",
"location": "",
"invitees": [
{
"id": "020",
"acceptance": "1"
}
]
}
],
"settings": [
{
"sync_frequency": "0"
}
]
}
]}
This is a valid json format. I have checked it with http://jsonlint.com/ and using http://braincast.nl/samples/jsoneditor/
see the structure of json value.According to structure the people tag should return count of 2, as it has 2 objects, but it is returning only 1 while parsing.
I am completely out of options. Please help guys.
This is the code i am using for parsing
NSString *textPAth = [[NSBundle mainBundle] pathForResource:#"sync" ofType:#"json"];
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPAth encoding:NSUTF8StringEncoding error:&error];
NSArray *jsonArray = [[content JSONValue] retain];
NSLog(#"JSON ARRAY %# AND COUNT %d",[[jsonArray valueForKey:#"updates"] valueForKey:#"people"],[[[jsonArray valueForKey:#"updates"] valueForKey:#"people"] count]);
I'm not sure why every dictionary is wrapped with an array, when there is only 1 entry (unnecessary), but if you want to parse it you'd want something like this:
NSDictionary *jsonDict = [[content JSONValue] retain];
NSArray *updatesArray = [jsonDict objectForKey:#"updates"];
NSDictionary *updatesDict = [updatesArray objectAtIndex:0];
NSArray *peopleArray = [updatesDict objectForKey:#"people"];
NSLog(#"People count: %i", [peopleArray count]);
for (NSDictionary *peopleDict in peopleArray) {
//do something
}
As a side note, if this is your JSON, you'll want to remove the [arrays] for entries that are not actually arrays. While you can still parse it, it means you'll have to read the array first then get the dictionary from the objectAtIndex:0, which is totally inefficient and pointless.
Could it be that every one of your objects is wrapped in an array and giving unexpected results?

IOS 5 JSON Parsing with sub level

I Try to parse a Json feed with IOS 5.
My Json File is like that :
{
"status": "ok",
"count": 18,
"count_total": 2248,
"pages": 125,
"posts": [
{
"id": 31781,
"type": "post",
"slug": "aaa",
"url": "http:\/\/www.example.com\/videos\/aaa.html",
"status": "publish",
"title": "my Title",
"title_plain": "My Title",
"content": "<p>Jdfkdfkjkjdfklfdkldfkldfklfkdld.<\/p>\n",
"excerpt": "Jdfkdfkjkjdfklfdkldfkldfklfkdlds.",
"date": "2012-01-26 07:38:29",
"modified": "2012-01-26 07:38:29",
"categories": [
{
"id": 4,
"slug": "videos",
"title": "Videos",
"description": "",
"parent": 0,
"post_count": 476
}
],
"tags": [],
"author": {
"id": 4,
"slug": "author",
"name": "Au Thor",
"first_name": "",
"last_name": "",
"nickname": "Au Thor",
"url": "",
"description": ""
},
"attachments": [
{
"id": 31784,
"url": "http:\/\/www.example.com\/wp-content\/uploads\/2012\/01\/primo.jpg",
"slug": "primo",
"title": "primo",
"description": "",
"caption": "",
"parent": 31781,
"mime_type": "image\/jpeg",
"images": {
"full": {
"url": "http:\/\/www.example.com\/wp-content\/uploads\/2012\/01\/primo.jpg",
"width": 620,
"height": 389
},
"thumbnail": {
"url": "http:\/\/www.example.com\/wp-content\/uploads\/2012\/01\/primo-150x75.jpg",
"width": 150,
"height": 75
},
"medium": {
"url": "http:\/\/www.example.com\/wp-content\/uploads\/2012\/01\/primo.jpg",
"width": 620,
"height": 389
},
"large": {
"url": "http:\/\/www.example.com\/wp-content\/uploads\/2012\/01\/primo.jpg",
"width": 620,
"height": 389
}
}
}
],
"comment_count": 1,
"comment_status": "open",
"thumbnail": "http:\/\/www.example.com\/wp-content\/uploads\/2012\/01\/primo-150x75.jpg"
},
I have access to Title, content... like that :
NSArray* latestArticles = [json objectForKey:#"posts"];
NSDictionary* Article = [latestArticles objectAtIndex:0];
NSString *Titre = [Article objectForKey:#"title"];
But how I can have access to attachement > image > full > url field ?
I'm lost, and new with JSON...
Thanks for your help
Haven't testest but I believe it would be.
NSArray *allPosts = [json objectForKey:#"posts"];
NSDictionary *firstPost = [allPosts objectAtIndex:0];
NSArray *allAttachments = [firstPost objectForKey:#"attachments"];
NSDictionary *firstAttachment = [allAttachments objectAtIndex:0];
NSDictionary *allImages = [firstAttachment objectForKey:#"images"];
NSDictionary *fullImage = [allImages objectForKey:#"full"];
NSString *urlString = [fullImage objectForKey:#"url"];
With NSJSONSerialization if you see [] the object will be an NSArray, if you see {} the object will be an NSDictionary.
You can also get it by
NSArray *posts=json[#"posts"];
NSDictionary *newArticle=posts[0];
NSString *title=newArticle[#"title"];
Remember Objective-c is actually c language with object oriented concepts. You can apply basic c code or basic c syntax too. :)

How to manage Facebook api response data

I am developing an app for iPhone and I am sending this url to facebook:
https://graph.facebook.com/search?type=checkin&access_token=ACCESS_TOKEN
and the facebook reply something like this:
{
"data": [
{
"id": "2081746282701",
"from": {
"name": "USER1",
"id": "xxxxxxxxxx"
},
"place": {
"id": "xxxxxxxxx",
"name": "\u03a0\u03b1\u03bb\u03bb\u03ac\u03b4\u03b9\u03bf",
"location": {
"city": "xxxxxxxx",
"country": "Greece",
"latitude": xxxxx,
"longitude":xxxxx
}
},
"application": {
"name": "Facebook for iPhone",
"id": "6628568379"
},
"created_time": "2011-05-25T01:22:00+0000",
"likes": {
"data": [
{
"id":"xxxxxx",
"name": TaggedUsers"
},
{
"id": "xxxxxx",
"name": "tagged user"
}
]
}
},
{
"id": "xxxxxxx",
"from": {
"name": "UserWhich puplish this",
"id": "740646984"
},
"tags": {
"data": [
{
"name": "XXXXXX",
"id": "xxxxxxxxxx"
}
]
},
"place": {
"id": "xxxxxxxxxxxxx",
"name": "xxxxxxxx",
"location": {
"latitude": xxxxxx,
"longitude": xxxxxx
}
},
"application": {
"name": "Facebook for Android",
"id": "350685531728"
},
"created_time": "2011-05-23T17:18:54+0000",
"likes": {
"data": [
{
"id": "xxxxxxx",
"name": "xxxxxxxxx"
}
]
}
}
}
My question is how I will manage this string to export long lat place and the user who checked in? I think that NSCaseInsensitiveSearch wont do the trick because there is no unique variable to search for. For example the "data" is placed at the start of the responsed string and before of each check in but its placed and before tagged user!
This is JSON: JavaScript Object Notation.
You can decode it easily into a NSDictionary or NSArray with the json-framework depending on the root element. After that it's a tree like structure depending on the JSON returned.
The mentioned framework provides an easy to use category for NSObject which offers the method JSONValue.
Example to decode the json you'v received:
NSString *myJson = #"...";
NSDictionary *decodedJson = [myJson JSONValue];
Now you can use fast enumeration or direct access(objectForKey:) to retrieve the data you are interested in.
NSArray *users = [decodedJson objectForKey:#"data"];
foreach(NSDictionary *user in users =) {
NSLog(#"user's id: %#", [user objectForKey:#"id"]);
NSDictionary *fromData = [user objectForKey:#"from"]);
NSLog(#"user is from: %#", [fromData objectForKey:#"name"]);
NSLog(#"user is from id: %#", [fromData objectForKey:#"id"]);
// and so on ..
}