How to decode JSON including \u escape characters as UTF8 NSString? - ios

I'm fetching JSON objects and saving them in NSString as follows:
// fetch JSON from a Wiki article
NSError *error = nil;
NSString *responseString = [NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:&error];
This is working in general but my responseString is full of \u#### escape characters, what I want is the corresponding UTF8 characters, e.g. \u2640 should be ♀.
What's the easiest way to decode all escape characters in my responseString?
UPDATE:
I read somewhere that I should try fetching the JSON with NSNonLossyASCIIStringEncoding instead of NSUTF8StringEncoding, but this lead to an error so I didn't get a responseString at all with this.
The error then is:
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)"

Don't fetch a string. Fetch data and convert is using NSJSONSerialization:
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSJSONSerialization handles all the quoting and escaping stuff automatically.
jsonObject will be an NSArray or NSDictionary, depending on the input data.
Remark: dataWithContentsOfURL blocks the current thread until the request is completely
finished (or timed out). If that is an issue, consider to use one of the asynchronous
methods of NSURLConnection to fetch the data.)

Related

Invalid JSON String that extracted from HTML [duplicate]

After testing, I can only get [NSJSONSerialization isValidJSONObject:] to return a positive on JSON data that I have already parsed with [NSJSONSerialization JSONObjectWithData:options:error:].
According to the official documentation:
isValidJSONObject returns a Boolean value that indicates whether a given object can be
converted to JSON data.
However, despite the fact that the objects I am attempting to convert from JSON to a NSDictionary convert fine, isValidJSONObject returns NO.
Here is my code:
NSURL * url=[NSURL URLWithString:urlString];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error=[[NSError alloc] init];
NSMutableDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if([NSJSONSerialization isValidJSONObject:data]){
NSLog(#"data is JSON");
}else{
NSLog(#"data is not JSON");
}
if([NSJSONSerialization isValidJSONObject:dict]){
NSLog(#"dict is JSON");
}else{
NSLog(#"dict is not JSON");
}
NSLog(#"%#",dict);
My log contains the following:
data is not JSON
dict is JSON
and then the output of dict, which at this point is a huge NSMutableDictionary object. No errors are generated when running this code, but isValidJSONObject seems to be returning the wrong value when run on data.
How can I get isValidJSONObject to work as expected?
isValidJSONObject tests if a JSON object (a NSDictionary or NSArray) can be successfully
converted to JSON data.
It is not for testing if an NSData object contains valid JSON data. To test for valid
JSON data you just call
[NSJSONSerialization JSONObjectWithData:data ...]
and check if the return value is nil or not.

JSON parsing iOS

I am having a problem in parsing JSON url in my iOS application
NSString *strUrl = [NSString stringWithFormat:#"http://www.google.com/finance/info?q=NSE:MARUTI"];
NSURL *url = [NSURL URLWithString:strUrl];
NSData *stockData = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableArray *arrStock = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:stockData options:kNilOptions error:&error];
The link returns an array but I am getting an empty array. Can anyone help please
The returned string is not valid JSON because it seems to begin with "// ".
Two things would help with debugging this:
When nil is returned examine (NSLog()) the error return.
NSLog(#"error: %#", error.localizedDescription); returns:
error: The data couldn’t be read because it isn’t in the correct format.
NSLog the returned data.
NSLog(#"data : %#", stockData);
data : <0a2f2f20 5b0a7b0a ...
Notice the leading "0a2f2f20".
or
NSLog(#"data as string: %#", [[NSString alloc] initWithData:stockData encoding:NSUTF8StringEncoding]);
data as string:
// [
{
"id": "7152373"
,"t" : "MARUTI"
Notice the leading "// " which is preceeded with newline character that is not obvious which is why I prefer the hex representation.

Get string out of json object of only string

I have a Json string which is only a string in Json format, like below:
#""JSONContent""
Is there a way to get the content out from such JSON string? I've tried to use below code but it cannot be parsed to Dictionary
NSData *jsonData = [rawTime dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
First of all, if that is the reponse that you are getting, then probably it wont be recognized as JSON because JSON strings start with a '[' or '{' character. Hence, it wont be parsed. You have to make sure that the string you receive from the server is in proper JSON format or not. You can check the JSON string validation on this website : jsonlint.com
Now the code that you have tried will also not work because of the same reason, i.e improper JSON format. There can be many reasons so as to why JSON that is received is in a bad format. It also might be possible that your JSON might be embeeded in an XML string like as shown :
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">
[{"Title":"DemoTitle","CreationDate":"06/06/2014","Description":"DemoDescription"}]
</string>
This is just an example. So the conclusion here is : Make sure your JSON is in proper format, i.e starting with '[' or '{'.
As for the parsing code, this might help you :
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
This will fetch the JSON response from the service URL and then parse it using NSJSONSerialization and finally store the data in an array for further use.
Hope this helps.

Cocoa error 3840 using JSON non latin characters being parsed

I already checked and my JSon is valid.
I try to pass it off to my app with this code
NSURL *actualURL = [NSURL URLWithString:[serverURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *errorJson;
NSData *data = [NSData dataWithContentsOfURL:actualURL options:kNilOptions error:nil];
jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJson];
I am getting the 3840 error code in the NSJSONSerialization
jsondata is (nonatomic, strong) NSMutableArray btw.
I tried many solutions I found online but it isn't working.
Does anyone have any ideas? I think the problem might be that some of the data being parsed are Greek characters (UTF8_unicode_cl collation on the server).
Here's my JSon example data btw
[{"diseaseID":"18","diseaseName":"test disease 1","diseaseDescription":"test disease 1 description","diseaseDoctor":"\u03ba\u03b1\u03c1\u03b4\u03b9\u03bf\u03bb\u03cc\u03b3\u03bf\u03c2","diseaseImagePath":"test disease 1"}]
Any ideas?

Json Parsing Failed

I am creating a simple Login page. In my project I want to parse the json string. But it gives me following error.
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=4
\"Valid fragment, but not JSON\"
UserInfo=0xa6e70a0 {NSLocalizedDescription=Valid fragment, but not JSON}"
In my code if I am putting another json string than it is working. And also my original json string is giving me the data in browser. So what to do?
My Code is:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://dev.bevbucks.com/gbs/api.json/token?user=rverma#prismetric.com&pwd=verma!pris"]];
NSURLResponse *response = nil;
NSError *error = nil;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//json parse
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSDictionary *jsonObject = [responseString JSONValue];
NSLog(#"type : %#", jsonObject );
The returned string:
"60ee094456b6fc03f386af50c443b471"
Isn't valid JSON, and should at least be:
[ "60ee094456b6fc03f386af50c443b471" ]
So there is a bug in the server, and not your code. If you cannot get this bug fixed then you're going to have to workaround it.
From JSON.org:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array.
An ordered list of values. In most
languages, this is realized as an array, vector, list, or sequence.

Resources