How to convert XML string to JSON using iPhone sdk - iphone

I am implementing a client based application. In that I have an xml string. I need to convert it to JSON format and send to the server. I have no idea on converting this. Can you guys please suggest me any documentation or idea to this?

Step #1: Read XML into NSDictionary: http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
Step #2: Convert NSDictionary into JSON: http://code.google.com/p/json-framework/

As Steve said the two steps are those, I leave you a bit of code, maybe can help you a bit more:
// Don't forget the imports ;)
#import "XMLReader.h"
// You must have a XML string from somewhere
NSString XMLString = yourXML;
// I remove all returns and tabs from the text, after i would be annoying if you don't remove it
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"\r" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"\t" withString:#""];
// Parse the XML into a dictionary
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:XMLString error:&parseError];
NSError *error;
self.dataParsed = [NSJSONSerialization dataWithJSONObject:xmlDictionary
options: NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
// Print the dictionary
NSLog(#"%#", xmlDictionary);

Related

How to generate a JSON string compatible with Objective-C syntax

I need some kind of json string generator for objective-c. Actually I thought there must be something like that but I could not find anything.To be specific, for example I have a json string like:
{"name":"abc","email":"def#ghi.com","password":"1"}
when I want to store it in objective c, I have to write it like:
#"{\"name\":""\"abc\""",\"email\":""\"def#ghi.com\""",\"password\":""\"1\"""}"
so it is confusing and hard to implement. Are there any generators or an easy way to implement it. Thanks
Convert your json string to dictionary...
NSData* data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"jsonDict:%#",jsonDict);
You can use the native ios SDK API's for generating JSON data from NSDictionary / NSArray.
e.g.,
NSData *jsondata = [NSJSONSerialization dataWithJSONObject:(dictobject) options:NSJSONWritingPrettyPrinted error:&error];
NSString *str = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
may this helps!
Use it
Also Import"JSON.H"
NSDictionary *googleResponse = [[NSString stringWithContentsOfURL:[NSURL URLWithString:website] encoding: NSUTF8StringEncoding error: NULL] JSONValue];
be careful...in your original question, when referring to how to store it in objective-c, i think you made a mistake
you wrote :
#"{\"name\":""\"abc\"""
when it shoud be
#"{\"name\":\"abc\",....etc...
i think you doubled the quotes...be wary, cause in the beginning there already is one opening double-quote #", all the other needed quotes must be escaped like so \", and then also have an ending quote as well.
hope it helps

JSON returning null

I'm having a bit of trouble parsing some returned JSON. I'm fairly new to working with JSON. I'm trying to get the company name from the first JSON array element. I have a feeling that I'm confusing the use of NSMutabeArray and NSMutableDictionary. What I get is null. Any idea what I'm doing wrong?
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSString* companyName = [[json objectAtIndex:0] objectForKey:#"name"] ; //Where I need some help
NSLog(#"we got %#", companyName);
Load that url in your browser. Looks like google is prefixing the JSON with //. I think NSJSONSerialization is tripping on that. Try this
NSRange range = NSMakeRange(2, [data length] - 3);
NSData *noPrefix = [data subdataWithRange:range];
Then send that to the parser.
You put in an error object, but you never looked at it. If you had, you would see that the data is corrupted:
Error Domain = NSCocoaErrorDomain Code = 3840 "The data couldn’t be read because it has been corrupted." (Invalid value around character 1.) UserInfo = 0x10030a8f0 { NSDebugDescription = Invalid value around character 1. }
I changed the value of the options parameter to see this error. I have
NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers |NSJSONReadingAllowFragments error:&error];

Parse json in objective-c for my iphone app

i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.

Convert NSData to JSON

I have a NSData object, i need to convert it a NSDictionary object.
NSData *data = ....;
Now i need to convert this to a NSDictionary, How can i do this programatically ?
note: After i save the NSData to the NSDictionary i should be able to access key value pairs of the NSDictionary.
I don't have a code to demonstrate my workings so far, I have only created the NSData object, and have no clue to continue :)
You can subclass MKNetworkOperation and override the responseJSON method with the following:
-(id) responseJSON
{
NSString *rawJSON;
id jsonValue = nil;
if ((rawJSON = [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding]) != nil) {
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if ((jsonValue = [jsonParser objectWithString:rawJSON]) == nil) {
NSLog(#"This string doesn't seem to be JSON: '%#'\nraw Data : '%s'", rawJSON, (char *)[[self responseData] bytes]);
return [self responseString];
}
}
else {
NSLog(#"This data doesn't seem to be an UTF8 encoded string: %#", [self responseData]);
return [self responseString];
}
return jsonValue;
}
Please check this link of stack overflow, I have already consumed the JSON services, it will help you a lot. All of the coding is there.
JSON Data Conversion
And here is the tutorial with sample project
JSON Parse Tutorial
Hope you would find it helpful
I highly recommend invoking SBJSON framework, it saved my time for many times, exactly finished my work and easily to use. You don't need to know the details of the conversion algorithm, just download and invoke it.
You might want to download it from here, then follow this tutorial to get your things done.

Extracting HTML Attribute from string iPhone

I have an html string that I get from the response of a website. Everything I do there works awesome and I have no difficulty. What I need to go is grab the only href attribute within the html. What is the best approach for getting this URL that is contained within that attribute. I am open to any external libraries if that is necessary, I just want the most efficient way possible. Thanks.
Use this API to parse the HTML code and pick the elements you want.
ElementParser is lightweight framework to provide easy access to xml and html content. Rather than get lost in the complexities of the HTML and XML specifications, it aspires to not obscure their essential simplicity. It doesn’t do everything, it aspires to do “just enough”.
Source: http://touchtank.wordpress.com/element-parser/
Here is an example of how to use the ElementParser with your own example. I hope this is helpful.
Merry Xmas! Ho-Ho-Ho
// Here you create the parser, don't forget to #import "Element.h" and #import "ElementParser.h"
ElementParser * parser = [[ElementParser alloc] init];
// This is the HTML source code that you want to parse
DocumentRoot* document = [parser parseHTML:#"<html>Google Link</html>"];
// Create an array where you will put all the <a></a> elements
NSArray* elements = [document selectElements: #"a"];
// Iterate though the array, for each element pick the "href" attribute
NSMutableArray* results = [NSMutableArray array];
for (Element* element in elements){
NSString* snipet = [element attribute:#"href"];
// Add the result for each element to the "results" array
[results addObject: snipet];
}
// Print the results on the screen
NSLog(#"%#",[results componentsJoinedByString: #"\n"]);
You could use NSRegularExpresion for extracting the url of the html tag.
NSString *regexStr = #"http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?";
NSString * url = #"stackoverflow";
NSError *error;
NSRegularExpression *testRegex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
if( testRegex == nil ) NSLog( #"Error making regex: %#", error );
NSRange range = [testRegex rangeOfFirstMatchInString:url options:0 range:NSMakeRange(0, [url length])];
NSString * href = [url substringWithRange:range];
Bear in mind that NSRegularExpression needs IOS 4 or 5.