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

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

Related

Latin characters display ? objective-c

I am making a call to get a JSON response like this:
NSData *urlData=[NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&httpResponse error:nil ];
NSString *returnString=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
However, when I print the string using NSLog:
Emiratos �rabes Unidos
When I convert it to NSData like this:
NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
NSArray * response = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
It turns it to be (when I retrieve the value from the array):
Emiratos \Ufffdrabes Unidos
And when I put it in a label it displays it like this:
Emiratos �rabes Unidos
I would like to display in a label like this:
Emiratos Árabes Unidos
How can I do it?
The problem seems to be this line:
NSString *returnString =
[[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding];
You are assuming that the data is a string encoded as UTF8. But apparently it isn't. Therefore you're seeing the "replacement character" (codepoint U+FFFD) at this point.
You'll need to find out what encoding is actually being used. You can probably just experiment with other encodings. Alternatively, use NSLog to look at the data; an NSData object is logged as a sequence of hex bytes, so by looking at the bytes in that position, and by looking up various encodings on the Internet, you may be able to deduce what encoding is being used here.
(But if you use NSLog and you actually see FFFD at this point, then you've had it; the server itself is supplying the bad data and there's nothing you can do about it, as the good data is lost before you can get at it.)

How to parse this type of data ios sdk [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
parse UTF-8 JSON ios sdk
[4,"1.0",1347139911696]
[0,"Neathouse Place","58226","STBC",154,"L",51.495322,-0.141808]
[0,"Vauxhall Bridge Rd / Victoria Stn","59516","STBC",160,"Z9",51.495931,-0.142216]
[0,"VICTORIA, VAUXHALL BRIDGE ROAD (EAST)",null,null,0,null,51.495839,-0.142119]
[0,"Vauxhall Bridge Rd / Victoria Stn","54249","STBC",256,"M",51.496573,-0.141354]
How to parse this type of data.
check this link.
It is UTF-8 JSON data type according to service provider. If its not then please tell me which type of data is it and how to parse it.
please help me out.
thanks.
The first thing to realize is that your data is actually 5 separate but valid JSON arrays. JSON can be validated at jsonlint.com.
To make something useful from them you must split your response by lines. You can use the newline character as a delimiter.
// stringWithContentsOfURL: used for demonstration
NSURL *sourceURL = [NSURL URLWithString:#"http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1?Circle=51.49598,-0.14091,100&StopPointState=0&ReturnList=StopCode1,StopPointName,Bearing,StopPointIndicator,StopPointType,Latitude,Longitude"];
NSString *actualResponse = [NSString stringWithContentsOfURL:sourceURL encoding:NSUTF8StringEncoding error:nil];
NSArray *individualJSONArrays = [actualResponse componentsSeparatedByString:#"\n"];
You now have an NSArray with 5 valid JSON NSStrings. You can either deal with any one of them, or convert them all to NS-Class objects by enumerating like so:
NSMutableArray *jsonObjects = [[NSMutableArray alloc] init];
for (NSString *jsonString in individualJSONArrays) {
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
if (jsonArray){
[jsonObjects addObject:jsonArray];
}
}
NSLog(#"%#",jsonObjects);
You now have an NSArray filled with NSArrays.

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.

Instance method '-jsonValue'not found (return type defaults to 'id')

I got problem in following statement.
NSArray *feedsData = [strFeedsResponse JSONValue];
I presume strFeedsResponse is an instance of NSString. There is no such method as JSONValue in NSString. You need NSString category and add the JSONValue method there.
You can use for example SBJson library https://github.com/stig/json-framework/, which contains NSString+SBJson.h header, which adds the JSONValue method for NSString.
This header must be than imported in the source file where you want to use the JSONValue method:
#import NSString+SBJSON.h
More about categories for example here: http://macdevelopertips.com/objective-c/objective-c-categories.html
One of two things is happening:
strFeedsResponse is not ACTUALLY an instance of an NSString. Maybe it is null or it has been initiated with an incorrect value. You can add a breakpoint to your code to check the value that is stored in strFeedsResponse before you call JSONValue on it.
You have not correctly imported the JSON framework that you are using into your class. You need to add the JSON header to your class.
Hope this helps future searchers on this error...
The reason for the error is that the current version of SBJson seems to not contain the NSString category "NSString+SBJSON.h" referred to by an earlier poster. So, you could easily write your own, or just use the SBJsonParser class directly ("address" is just an NSString containing something like "24 Elm Street, Yourtown, New Mexico"):
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSString *response = [NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *googleResponse = [parser objectWithString:response];
Cheers!
If you are using a webservice, then give the URL for that.
try this way...
NSArray* latestentry = (NSDictionary*)[responseString JSONValue];
NSArray *feedsData = [[strFeedsResponse JSONValue] mutableCopy];
Use this Line, it will be useful to you..
This error generally comes when method not found.Here it comes because JSONValue function is not found.
Please make sure you have included json header files where you calling this function.

How to convert XML string to JSON using iPhone sdk

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);