I am trying to parse the JSON returned here: http://www.waterwayguide.com/map/php/bridge.php?ll=25.514339,-80.076164
However, I can't parse it as I normally would it seems:
NSData *jsonData = [[(ASIHTTPRequest*)[data objectForKey:#"request"] responseString] dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSLog(#"this prints as expected %#", [(ASIHTTPRequest*)[data objectForKey:#"request"] responseString]);
NSArray* jsonNodes = [[CJSONDeserializer deserializer] deserialize:jsonData error:&error];
NSLog(#"this is unexpectedly nil %#", jsonNodes);
I have used this precise code on a different JSON feed and it works nicely. Is there something I can do on the client side to parse this feed properlY?
That feed isn't JSON. Look at the source. It's text/html and it doesn't validate because it attempts to escape ' with \'. Altogether, it seems to be a quick attempt to manually output JSON instead of HTML.
Related
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.)
I'm trying to parse the JSON file at this URL: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=results
The code that I have so far is as follows:
NSData *data=[NSData dataWithContentsOfURL:[[NSURL alloc] initWithString:url]];
NSError *error = nil;
id myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", error);
NSArray *jsonArray = (NSArray *)myJSON;
for (id element in jsonArray) {
NSLog(#"Element: %#", [element description]);
}
This code seems to come up with an error each time (ERROR 3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)").
I'm wondering if this is a problem with the way that I'm downloading/parsing the data or if it's a problem within the actual JSON in which I have to approach it in a different matter.
Remove the &callback=results at the end of the URL. This causes the JSON to not start with an array or dictionary. Just be aware that if you are referencing "results" in your JSON code then you will need to remove/change that. If you diff the two JSON texts then you will see the difference (look at the beginning).
in a web browser open the result of the url you posted copy the contents then go to jsonlint.com and paste the contents then click validate. it shows you that the input is not valid json so you might have to do some additional parsing.
I have an app that just opened call a webserver page that gives me a json string.
When I'm on the local network all works without problem but when I open the app outside the local network and without vpn the app crashes.
How can I control the json string?
This is my code:
NSString *urlstr = [[NSString alloc] initWithFormat:#"%#yes.php", av];
NSURL *url = [[NSURL alloc] initWithString:urlstr];
NSError* error = nil;
NSString* urlString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSString *newStr;
NSData* data=[newStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
sn1 = [[json objectForKey:#"Rele1"] intValue];
I want to compare the json answer with a NULL value, if the two parameters are equal I show an alert.
EDIT: If I try to read any value, the app crashes waiting the json reply...
I have bypassed the problem with an NSURLRequest with the timeoutInterval parameter that closes the connection after n seconds.
Amongst other things, you fail to:
check whether the attempt to fetch an ASCII-encoded string from a remote URL failed (obvious possibilities: the URL is unreachable, the result is UTF-8 rather than ASCII);
check whether the JSON parsing succeeds (obvious possibility: the server 404d and returned an HTML error page instead)
check whether the returned JSON object was actually a dictionary (eg, it could be an array, in which case calling objectForKey: on it will raise an exception)
The parsing of return data as ASCII then re-encoding into UTF-8 is also probably redundant — because the one supersets the other it has the effect of a threshold test, otherwise preventing acceptable results from proceeding.
Does this code ever worked?
You should check error after [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
you are reading URL data into urlString but then get NSData from uninitialized newStr and parse it?
again you should always check error whenever you provide it before anything else
why do you read the data as ASCII but the NSData as UTF8?
Already i have worked on SBJSON parsing, that was working very fine. Now, i am working in SBJSON parsing. The problem is the parsing result is returning null(In NSDictionary). I have tested the url in Firefox POST tool, it returned result with the Content-Type = application/x-www-form-urlencoded and Method = POST. How to use Content-Type and Method[POST, GET] in SBJSON file parsing? Really i can not find the result in google search(sorry). Please help me to solve my problem. Please suggest me any sample code or idea. Thanks in advance.
This is my code,
SBJSON *jsonParser = [[SBJSON new] autorelease];
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"SAMPLE URL"]];
NSString *stringUrl = [NSString stringWithFormat:#"%#",urls];
NSDictionary *dictionary = (NSDictionary *) [jsonParser objectWithString:stringUrl error:nil];
NSLog(#"Dictionary : %#", dictionary);
The dictionary is returning null. How to use Content-Type and [POST,GET] methods in SBJSON file parsing?
Thanks in advance.
You are not actually fetching the string data at the URL, just creating a URL and parsing that, which unsurprisingly, cannot be converted to a JSON object. You should asynchronously fetch the string data using something like NSURLConnection, or easier ASIHTTP, then parse the result.
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);