0

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];
1
  • 1
    options:nil is wrong, the types don't match (nil is an object, whereas options: expects an integer -- a bitmask, specifically.) - Apart from that, you should read the documentation of that very argument. If you had read it, you would have noticed the NSJSONReadingAllowFragments option which does exactly what you want. Commented Aug 3, 2014 at 5:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When you say "start with { or [" you mean "must use a dictionary or array as the top-level object". Or no?
Yes. Thats because otherwise, your JSON wont be parsed as it will not be recognized as a valid JSON string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.