Json Parsing Failed - ios

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.

Related

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.

Creating a route with JSON data given user input

I am looking to use JSON data to create a route using the Google Maps API and extract JSON data that will be displayed onto a text field that includes "distance" and "duration". I would like to have to text fields that will reverse geocode and send a request to the Google Map API. Here is an example code I'm using:
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses) {
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"text"], [[status objectForKey:#"user"] objectForKey:#"screen_name"]);
}
Rather than it print onto the screen I would like for this to print onto a text field while gathering specific data from the JSON data. I would also like to be able to reverse geocode.

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

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

Correctly Handle UTF-8 In JSON on iOS

I'm receiving some JSON that has weird UTF-8 strings. Eg:
{
"title": "It\U2019s The End";
}
What's the best way to handle this data so that it can be presented in a readable way? I'd like to convert that \U2019 into the quote mark that it should represent.
Edit:
Assume I have parsed the string into a NSString* jsonResult
Edit 2: I'm receiving the JSON through AFNetworking:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSString* jsonResult = [JSON valueForKeyPath:#"title"];
} failure:nil];
Update:
Kurt has brought to attention that AFJSONRequestOperation uses NSJSONSerialization under the hood. As such, it's probably the case that your JSON is invalid (as mentioned below, there shouldn't be a ;, and the U should be a lowercase u. This was mentioned in the original answer below.
It's part of the way JSON is able to store its data. You will need to pass your JSON string through a JSON parser, then you will be able to extract your string correctly.
Note: The JSON you've posted above is invalid, there shouldn't be a semi-colon at the end, and the U should be a lower-case u; the example below has a modified JSON string
NSString* str = #"{\"title\": \"It\\u2019s The End\"}";
NSError *error = nil;
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *rootDictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
if (error) {
// Handle an error in the parsing
}
else {
NSString *title = [rootDictionary objectForKey:#"title"];
NSLog(#"%#", title); //Prints "It’s The End"
}

access NSMutableDictionary value without key?

quite new to iOS development and objective-c at the same time. I have the following method:
-(NSMutableArray *)fetchDatabaseJSON{
NSURL *url = [NSURL URLWithString:#"http://www.ios.com/ios/responseScript.php"];
NSError *error = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:&error];
//jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//NSLog(#"Array: %#",[jsonArray objectAtIndex:0]);
jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Dictionary: %#", jsonDictionary);
return jsonArray;
}
Now the NSLog shows this:
2013-02-03 19:15:37.081 TestConnection[24510:c07] Dictionary: (
Bannana,
Apple,
SomeCheese )
From what I understand that whatever is inside the dictionary doesn't have key-value. How can this be? and how can I fix it? I want to be able to have keys to ease operations on dictionary.
Regards,
JSONObjectWithData may return an NSArray or NSDictionary, depending on the JSON data you give it. If your JSON string is an array, you will have an NSArray. If your JSON data is a dictionary, you will get an NSDictionary.
Convert your JSON data (your data variable) to string and print it out with NSLog. To convert NSData to NSString, use something like:
NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
If you print it out and see a JSON array, you simply don't have a dictionary there.. If you can alter the server-code that generates the JSON, you may be able to change that.
One more thing I noticed, you assume that the returning container is mutable. If I'm not mistaken, you need to use an option like NSJSONReadingMutableContainers in the options parameter of JSONObjectWithData to get that.
One last tip, if you want to check in code if you have an NSArray (or NSDictionary), use something like:
if ([obj isKindOfClass:[NSArray class]]) {...}

Resources