Creating Objects from JSON - iphone

I would like to be able to create an NSArray or NSDictionary with a JSON string that I receive from a web service. I am using the json framework to do this. The response string will look something along these lines:
{count:2,
data:[{"ID":8,
"Title":"Test Title",
"Author":"Test Author",
"Price":"18.00",
"Edition":"1st",
"Condition":"Good",
"UploadDate":"2012-07-28 07:25:56.0"
},
{"ID":9,
"Title":"Test Title",
"Author":"Test Author",
"Price":"18.000000000000",
"Edition":"1st",
"Condition":"Good",
"UploadDate":"2012-07-28 07:27:06.0"
}
]
}
My question is, what is the most efficient way to grab all of the data from the 'data' array and use it to create either an NSArray or NSDictionary? Any help would be much appreciated

I use RestKit for JSON parsing. It has all you need to fetch the json from a server, translate it into a dictionary, and from there into an object that you can work with. That might be more than you dared to wish for, but it works like a charm. Check out https://github.com/RestKit/RestKit for more info.

Starting from iOS5 a json parser has been integrated as a SDK native component see the following link http://www.raywenderlich.com/5492/working-with-json-in-ios-5.
You will create a NSDictionary with 2 keys "count" and "data" and then you will get the NSArray using objectForKey with the "data" key.

Related

iOS JSON parser: what happens if two keys have the same name?

if the server returns:
{
"repositories":
{
"xmlns":{...}
"repository":{...}
"repository":{...}
}
}
then is it a valid JSON? I tested it in This JSON Parser and it works fine, but I wonder when I use some parser to parse it and get an NSDictionary, then for the key 'repository', how do I get the two repositories?
Thanks!
That JSON parser is not good then, the last value will overwrite the first one. Use JSONLint instead to validate your JSON, you will see the result.

How we can handle dynamic web service in iPhone?

I am learning some tricky development in iPhone and during my experiments I found out that usually we used localized web-service in which all parameter are fixed(Keyword). If my web service will change some fields in the response than how can we handle in iPhone. Please help me. If Anybody have any good idea.
For Example,
Webservice Response1:
[    {
      "Number":"A12 hrb",
      "List":[
         {
            "Type":"Works",
            "Display":{
               "dop":45,
               "dopper":56
            },
            "OAST":"10-01-2012",
            "OAET":"07-04-2012",
            "Cause":"define",
            "Impact":"Queue",
            "Description":"Take a Break.",
            "LName":"Lunetten To Lunetten",
            "Number":"A12 hrb",
         }
      ]    },   ]
Webservice Response2:
[    {
      "Number":"A12 hrb",
"Number2":"A13 brs",
      "List":[
         {
            "Type":"Works",
            "Display":{
               "dop":45,
               "dopper":56
"picker":90
            },
            "OAST":"10-01-2012",
"MAET":"07-04-2012",
            "OAET":"07-04-2012",
            "Cause":"define",
            "Impact":"Queue",
            "Description":"Take a Break.",
            "LName":"Lunetten To Lunetten",
            "Number":"A12 hrb",
         }
      ]    },   ]
You can do this
Parse the response.If response is JSON then definitely you will get a dictionary just keep a reference of it.
you can get all the keys in dictionary by calling following method
(NSArray *)allKeys
now enumerate above array and access the values respective to each key and do whatever you want
But you should know the meaning/purpose of dynamic keys. If you don't no meaning/purpose of keys these steps may not help you... best of luck.
For this type of case you can get the dictionary and in dictionary you
can get the value of which tag you want means you just need root node
and store root node all the data in dictionary and handle that
dictionary for the further use..
I don't think it will be possible to parse it completely. Atleast you should know which keys are going to be there. e.g. response has Number, Number2 & List as keys. It's ok if some responses do not contain one/some of the keys.
On the other hand, if knowing all the keys in advance is at all not possible, then webservice should have mechanism to convey the keys used in response.
e.g. [ {
"dynamic_keys": "Number2",
"Number":"A12 hrb",
"Number2":"A13 brs",
"List":[
{
"Type":"Works",
"Display":{
"dop":45,
"dopper":56
"picker":90
},
"OAST":"10-01-2012",
"MAET":"07-04-2012",
"OAET":"07-04-2012",
"Cause":"define",
"Impact":"Queue",
"Description":"Take a Break.",
"LName":"Lunetten To Lunetten",
"Number":"A12 hrb",
}
] }, ]
You can read the value of "dynamic_keys" and then using that value you can read value of actual dynamic key.
edit: as mentioned by ssteinberg you can use some framework like JSONKit to parse actual JSON.
See this as well: How to parse JSON having dynamic key node

Graph API - get JSON data without "paging" key

I'm getting facebook data using graph api, adding fields in string and get JSON result.
Example:
https://graph.facebook.com/me?fields=music
But JSON returned contains a "paging" key and I do not I want this key.
{ "music":{
"data":[
{
"name":"",
"category":"",
"id":"",
"created_time":""
},
{
"name":"",
"category":"",
"id":"",
"created_time":""
}
],
"paging":{
"next":"https://graph.facebook.com/me?fields=music&method=GET&metadata=true&format=json&callback=___GraphExplorerAsyncCallback___&access_token=...&limit=5000&offset=5000&__after_id=..."
}}}
EDITED:
I'm using Java API (restfb.com) to get JSON.
The command in java is:
FacebookClient client = new DefaultFacebookClient("ACCESS_TOKEN_HERE");
JsonObject rMusic = client.fetchObject("ID_HERE", JsonObject.class, Parameter.with("fields", "id,name,religion,birthday,music"));
How do I avoid it or remove it?
When you have your Javascript object built from the JSON, just pay attention to the array of data: result.music.data
And forget about the paging property: result.music.paging
Remember, there's no law in coding that you have to look at every property in your scripts.
Based upon the edit to the question above, here's a new answer.
The Rest API is deprecated. You should upgrade your app to use the Graph API as this is the one being supported.
Also, if you see a property you don't like, you don't have to access it. Remember, there's no law in coding that you have to look at every property in your scripts.

oData Objective-C add a JSon stream

I try to add a Json strem form my odata server.
It work fine with jQuery, but in objective-c ther is only xml returned.
I try this :
DataModel *proxy = [[DataModel alloc] initWithUri:#"http://www.example.com/odata/odata.svc" credential:nil];
[proxy addHeader:#"Accept" headerValue:#"application/json, text/javascript, */*; sq=0.01"];
QueryOperationResponse *response = [proxy execute:#"Example"];
NSMutableArray *array = [response getResult];
It doesn't work.
How can I do?
thanks
Gwennin
xml is what odata will return. you will need to parse the results. Here is a link to a great tutorial for doing that.
http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project
If the returned type is a Collection<> of some sort, the OData library does the work for you and converts it to an array of the correct Entity in Objective-C.
If you return a simple type, parse the result. An example is using XPath queries (although for my service, I had to remove from the returned XML a couple of unsupported root element attributes that Odata returned).
If you chose to use Xpath,I love this code: http://cocoawithlove.com/2008/10/using-libxml2-for-parsing-and-xpath.html

How to Separate HTML Response

I am using FConnect in my app. After the user logs in to his/her Facebook account I am getting his/her information as:
{
"id":"###########",
"name":"Vishnu Gupta",
"first_name":"Vishnu",
"last_name":"Gupta",
"link":"facebook a/c link id=#######",
"education":[{"school":{"id":"######","name":"st.joseph"},"type":"High School"}],
"gender":"male","email":"##########",
"timezone":5.5,
"locale":"en_US",
"verified":true,
"updated_time":"2010-11-27T10:10:25+0000"
}
I want to store user's information in database. To do that, I have to separate the user's information that is id, name, and email.
I tried using componentsSeparatedByString method but I do not understand how to retrieve the information in an array.
Can anyone help me????
The response you are getting is in JSON Format which basically have response in Array & Dictionary.
You will be getting this data in Dictionary..so you can access it by using the key value..
NSLog(#"%#",[NSDictionaryObject valueforkey:#"id"]);
NSLog(#"%#",[NSDictionaryObject valueforkey:#"name"]);
NSLog(#"%#",[NSDictionaryObject valueforkey:#"first_name"]);
Hope this will surely work for you.....
ya.....its corrrect.In detail:
Add JSON SDK then write the below code
SBJSON *json = [[SBJSON alloc] init];
NSDictionary *returnObject = [json objectWithString:InfoName];
NSString #id=[NSString stringWithFormat:#"%#",[returnObject objectForKey:#"id"]];
same for name ,email.
then Add these objects to Array and release the json
JSOn is good to use for "key-value' pair parsing.