Iphone:how to create json in Objective c - iphone

I am working on iPhone App.I have to return json string to a webservice in following format from Iphone.I am using Objective-C
{
"InspectionDetails":
[
{"isCompleted":"Y","QMSStepId":"1A","QMSEmpId":"6","QMSInspectionID":"1","InspectedDate":"07/28/11 09:52:34", "isNewRoom":"1","RoomInspID":"1","QMSRoomId":"1","QMSScoreId":"4"},
{"isCompleted":"Y","QMSStepId":"1B","QMSEmpId":"4","QMSInspectionID":"1","InspectedDate":"07/28/11 09:52:34", "isNewRoom":"1","RoomInspID":"1","QMSRoomId":"1","QMSScoreId":"3"}
],
"InspectionComments":
[
{"QMSPredefinedCommentId":"1","customText":"Test1 Comment","RoomInspID":"1"},
{"QMSPredefinedCommentId":"2","customText":"Test2 Comment","RoomInspID":"1"}
],
"Tools":
[
{"Facility_Code" : "1","HddId" : "AIPH01"}
]
}
can any one please help me how can I form the above response?
I have an idea that I can do this by using NSArray and NSDictonary but I want all the arrays in one dictionary. Can anyone please guide?
Thanks,
Shradha

The easiest way is to use something like SBJSON. Then you can just do
NSString *jsonString = [myDictionary JSONRepresentation];

I recommend using JSONKit (https://github.com/johnezang/JSONKit), it works very well and is speedy enough to serve common needs.
Suppose you have a NSDictionary like:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:
[NSArray arrayWithObjects:,#"anotherDict",#"anotherDict1",#"anotherDict" nil]
forKeys:[NSArray arrayWithObjects:#"Key1",#"Key2",#"Key3", nil]];
then you can simply get your JSON representation as follows: NSString *jsonString = [dict JSONString].
Read the documentation to get additional features.

Related

How to parse Json object

I'm stuck at json object parsing really tried hard. The problem is how to parse the json object. Here's what i get the response in the log.
{"0":{"**title**":"Test Event","url_title":"test_event1","status":"open","entry_date":"Sep 10, 2012,
05:20:38AM","entry_id":"26","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News &
Events","channel_name":"news_events","start_date":"1348120800","end_date":"1348120800","start_time": "43200","end_time":"46800","where":"FCF","news_event_description":"<p>\n\tLunch with group.<\/p>\n"},
"1":{"**title**":"Test Event 2","url_title":"test_event_2","status":"open","entry_date":"Sep 10, 2012, 05:20:08AM","entry_id":"28","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1348207200","end_date":"1348207200","start_time":"43200","end_time":"46800","where":"FCF - Lunch","news_event_description":"<p>\n\tThis was a great event.<\/p>\n"},
"2":{"**title**":"Test Event 3","url_title":"test_event_3","status":"open","entry_date":"Sep 10, 2012, 05:20:54AM","entry_id":"29","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1346738400","end_date":"1346738400","start_time":"7200","end_time":"11700","where":"FCF - Lunch","news_event_description":"<p>\n\tFall planning season.<\/p>\n"}}
The problem is i want to show all the titles in the tableview. I can get the single Title by using key 0,1,2. But i want all the titles to be shown at once i parse
Please help me out guys, Thanks in advance.
Suppose jsonDict is your json dictionary.... Try this
NSArray * keys=[[NSArray alloc]init];
keys=[jsonDict allKeys];
NSMutableArray *titles=[[NSMutableArray alloc]init];
for(int i=0;i<[keys count];i++){
[titles addObject:[[jsonDict valueForKey:[keys objectAtIndex:i]]valueForKey:#"title"]];
}
NSLog(#"your array of titles : %#",titles); //use this array to fill your cell
Are you trying to parse the JSON yourself? You might find it easier to use something that's already well tested, such as TouchJSON or Apple's own NSJSONSerilization. The result should be a graph of Objective-C objects that you can use however you like.
In any case, what you've got there is the equivalent of a dictionary of dictionaries. If you have that as a NSDictionary called myJSONDictionary, you can say:
NSArray *theObjects = [myJSONDictionary allValues]; // gets all the objects
NSArray *theTitles = [theObjects valueForKey:#"**title**"]; // gets all the titles
You can also iterate through a dictionary using fast enumeration:
NSMutableArray *theTitles = [NSMutableArray array];
for (NSString *key in myJSONDictionary) {
NSDictionary *object = [myJSONDictionary objectForKey:key];
NSString *title = [object objectForKey:#"**title**"];
[theTitles addObject:title]
}
There's no real advantage to doing that instead of using KVC as in the first example if you just need the titles, but it could be the right choice if you have more complex work to do for each object.

iPhone Programming - complex JSON Parsing - UITableView

Hey guys :) I am quite new to stack overflow and iPhone programming. I am trying to parse a complex JSON to display some stuff in the UITableView.
a part of the JSON structure -
{"1":{"1":"Ent1","done":"No"},"2":{"1":"Ent2","done":"No"}}
I am able to parse through the main keys "1" and "2" and able to grab the values corresponding to the key "1" inside {"1":"Ent1","done":"No"}, {"1":"Ent2","done":"No"} store them into a dictionary/ a string with the following code :
for (NSString *key in dict)
{
NSString *answer = [dict objectForKey:#"1"];
NSLog(#"%#", answer);
}
The result is Ent1 and Ent2 because the code iterates over the for loop and checks for the objects with key "1".
The problem is this - I want to store both the values(Ent1 and Ent2) into an array.
I use the following code:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: answer, nil];
but it just takes the last index in the dictionary which is Ent2.
Could you please tell me how could I add both the values for key 1 into an array?
Thanks in advance :)
To add to jamapag's answer, you can also use JSON libraries in objective C which do all the work for you like SBJSON or YAJL, or even as part of the more recent versions of the mac/iOS SDKs, NSJSONSerialization.
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSString *key in dict)
{
NSString *answer = [dict objectForKey:key];
[array addObject:answer];
}

YAJL - JSON on iOS/iPhone

In my iPhone app, I am trying to use the JSON library (YAJL) to create a JSON string that looks like the following format:
{"user":
{"name":"Jon", "username":"jon22", "password":"passw#rd", "email":"jon22#example.com"}
}
But I can't figure out the YAJL methods to create this.
I have tried the following:
NSArray *params = [NSArray arrayWithObjects:#"Jon", #"jon22", #"passw#rd", #"jon22#gmail.com", nil];
NSArray *keys = [NSArray arrayWithObjects:#"name", #"username", #"password", #"email", nil];
NSDictionary *userDictionary = [NSDictionary dictionaryWithObjects:params forKeys:keys];
NSString *JSONString = [userDictionary yajl_JSONString];
However, the returned string is not wrapped in the outside "user".
How can I use YAJL to create this json string? Does anyone have experience with this???
Many thanks,
Brett
I don't use YAJL, but SBJSON, which is the one Apple uses in iOS too...
Anyway, the library is behaving correctly: you're not creating an "user" dictionary!
You need to do something like:
NSDictionary *serialize = [NSDictionary dictionaryWithObject:userDictionary forKey:#"user"];
And then "JSON-ize" this one.
This is because when you call -yajl_JSONString on userDictionary, you are using userDictionary as your "root object". If you want to wrap this inside another dictionary, you need to explicitly do so.
I highly recommend that you check out JSONKit https://github.com/johnezang/JSONKit I have used numerous JSON parsers and have found it to be the easiest.
Also the documentation is awesome.

using Json in iphone app

I am trying to use Json in my iphone projects ,
but i didnt get how can I start using json in my project.
help me out from this condition.
Thanks in advance.
Well if you want you can get started by this
http://iosdevelopertips.com/networking/iphone-json-flickr-tutorial-part-1.html
this tutorial will help you understand what json does, but if you want to started on using it in your code than you should use the following example:
April 26, 2009
Dealing with JSON on iPhone
You can easily use the JSON (JavaScript Object Notation) data format in client-server communications
when writing an iPhone app. This blog is not suggesting that JSON is a more superior format for data
exchange than its counterparts such as XML. In fact, we have many projects that don't use JSON.
However, handling JSON is relatively straight forward in ObjectiveC.
Unfortunately, Apple iPhone SDK (as of this writing, the latest is iPhone 2.2.1) doesn't come with
a built-in JSON parser. But I found out a good one called json-framework. It is both a generator
and a parser. As a generator, json-framework can create JSON data from an NSDictionary. As a parser,
you can pass to json-framework an NSString that consists of JSON data and it will return a
NSDictionary that encapsulates the parsed data.
Next, I'm going to show you several examples. Before you proceed, download the library and make
sure you add it to your SDK path list (see INSTALL file that comes with it). If setup properly,
you should be able to start using the library by importing its header file:
#import "JSON/JSON.h"
Consider the following code:
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
#"grio", #"username",
#"hellogrio", #"password",
nil];
This instantiates a new dictionary which we'll turn into a JSON string. To do so, you'll need to
use a function called JSONRepresentation. This function is added as a category to NSObject. It
means that as long as there's an import of JSON.h file, you can call the function on any NSObject
object.
NSString* jsonString = [requestData JSONRepresentation];
And this is what you got when you print (NSLog(#"%#", jsonString);):
{"username":"grio","password":"hellogrio"}
Parsing is just as simple. Consider the following JSON data:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
Assume that this is the data that you received from a web service called and is currently stored
in an NSString called jsonResult. To parse it, you need to create SBJSON object and call one of
its initialization method, objectWithString.
SBJSON *json = [[SBJSON new] autorelease];
NSError *jsonError;
NSDictionary *parsedJSON = [json objectWithString:jsonResult error:&jsonError];
If parsing fails for reasons such as invalid construct of JSON format, jsonError variable will
be filled with the error info. If it is successful, parsedJSON will contain keys whose values
are either an NSString or NSDictionary. Let's look at the inside of parsedJSON:
NSDictionary* menu = [parsedJSON objectForKey:#"menu"];
NSLog(#"Menu id: %#", [menu objectForKey:#"id"]);
NSLog(#"Menu value: %#", [menu objectForKey:#"value"]);
And here's the output:
Menu id: file
Menu value: File
Observe the JSON data again. popup is an NSDictionary which has an array of menuitem.
NSDictionary* popup = [menu objectForKey:#"popup"];
NSArray* menuItems = [popup objectForKey:#"menuitem"];
NSEnumerator *enumerator = [menuItems objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(#"menuitem:value = %#", [item objectForKey:#"value"]);
}
And this is the output:
menuitem:value = New
menuitem:value = Open
menuitem:value = Close
Sorry i forgot the link to this website
json-framework is also good if you don't like TouchJson
I use ASIHttpRequest to make an Asynchronous call to my Web Service. In my requestFinished method I parse the JSON I received from my call and from there you can do pretty much anything with the JSON you received.

Parse JSON collection from Rails in Objective-C on iPhone

I'm using TouchJSON to parse the output of a JSON Rails API, but am having difficulties. The overall goal is to loop through the response, parse the JSON, create a Round instance for each JSON object, and stick those Round objects into an NSArray so I can load this into a UITableView. So if there's a more straight-forward way to do that than what I'm about to show (which currently is NOT working, btw) please let me know.
The Rails API is returning a collection that looks something like this:
[
{
"round": { "course_title": "Title A", "result": "+8" }
},
{
"round": { "course_title": "Title B", "result": "+4" }
},
...
]
I'm also using ASIHTTPRequest and I can successfully get the response using:
NSString *responseString = [request responseString];
But from there, I cannot seem to get anywhere. Here's more-or-less what TouchJSON suggests:
NSString *jsonString = [request responseString]; // [{"round":{...}}, ..., {"round:{...}}]
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil];
// then I do this...
NSLog(#"JSON: %#", dictionary); // JSON: null
I thought from there I would be able to loop through the dictionary and create the object mappings using my Round class. But maybe that's the wrong approach altogether.
My thoughts are that the JSON being returned from Rails is an array of JSON objects, so maybe that's why the JSON parser doesn't recognize it as valid JSON? From this, I have two questions:
1) Should TouchJSON be able to accept an array of JSON objects like what my API is returning?
2) Is it possible to cast the responseString to an NSArray so I can loop through each "round" and parse the JSON that way? If I remove the first and last characters from the response string (i.e. "[" and "]") the JSON parser will only grab the first "round" in the collection.
3) Am I going about this whole process correctly?
Any tips/advice would be much appreciated.
TouchJSON presents three main ways to go from JSON to an Obj-C object. They are all present in the header for CJSONDeserializer which you're already using:
- (id)deserialize:(NSData *)inData error:(NSError **)outError;
- (id)deserializeAsDictionary:(NSData *)inData error:(NSError **)outError;
- (id)deserializeAsArray:(NSData *)inData error:(NSError **)outError;
The first one will return return whatever, either a dictionary, array, string or whatever the root type of the JSON is.
The other two expect a dictionary or an array and will complain (i.e. return nil and give you an NSError) if they don't get the right data.
The deserializeAsDictionary:error: method of CJSONDeserializer relies on the scanJSONDictionary:error: method of CJSONScanner. This method expects the "dictionary" to be an object literal. Therefore, your data must start with a {. Since your data is an array, you would want to use the deserializeAsArray:error: method of CJSONDeserializer.
Read the documentation carefully, your code is incorrect. It should look like this:
NSData *jsonData = [request responseData]
NSArray *rounds = [[CJSONDeserializer deserializer] deserialize:jsonData error:nil];
// then I do this...
NSLog(#"JSON: %#", rounds);
You could also have used:
NSArray *rounds = [[CJSONDeserializer deserializer] deserializeAsArray:jsonData error:nil];
However your absolute BIGGEST mistake was passing nil for error. You could have avoided going to stackoverflow at ALL if you had passed something in for NSError and then checked that.
With the right tools, this is WAY simpler than you're making it. I do this sort of thing all the time.
Use Stig's JSON framework, and import the NSString category that provides the JSONValue method.
Then inside your ASIHTTPRequest response handler code, go thusly:
NSMutableArray *roundlist = [NSMutableArray array];
NSArray *results = [[request responseString] JSONValue];
for (NSDictionary *item in results) {
Round *myRound = [item objectForKey:#"round"];
//don't actually do the above. Do whatever you do to instantiate a 'Round'.
[roundlist addObject:myRound];
}
[self.tableView reloadData];
EDIT: Geezo. Objection noted re valueForKey: vs objectForKey:. I updated my code sample, and I think we all learned something here.
I also didn't mean any offense with the phrase "with the right tools". OP was looking to simplify his code, and the RIGHT TOOL for that is the library with the simplest interface. I have nothing against TouchJSON per se, but JSON Framework has the simpler interface.