1

I am using following code snippet to parse JSON object from the url.

   NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlAddress] options:NSDataReadingUncached error:&error];
    if (error != nil) {
        NSLog(@"%@",[error localizedDescription]);        
    }   else {
        NSLog(@"No Error: %@", data);  //looks good here. console displays the raw data 
    }

    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    if (error != nil) {
        NSLog(@"%@",[error localizedDescription]);
        return nil;

    }   else {
        NSLog(@"No Error: %@", [result objectForKey:@"exams"]); //console displays the value ("No Error: value for key...") unless a degree symbol is present in which case it displays No Error: (null)

    }

I have some 10 urlAddresses,for 7 urls JSONObjectWithData returns json object.for remaining 3 urls JSONObjectWithData returns null.I tried opening this urls in safari.I have seen some junk characters in it.I suspect problem is with this junk character.How to solve this issue?

I have seen this "JSONObjectWithData returns null if degree symbol is in json object" link similar.suggested to use unicode escape sequence.How to use this "unicode escape sequence" to solve my issue.

Community
  • 1
  • 1
Akbar
  • 1,509
  • 1
  • 16
  • 32
  • Probably an encoding problem. Does the server send the data in UTF-8 encoding? Can you give an example of a URL or data that cannot be converted? – Martin R May 15 '13 at 06:48
  • sorry martin,my url is confidential,but I can share the part of data as given below "Tarang Bharadwaj. Tarang's prot�g� and childhood friend Sargam",Here prot�g� has weird chars. – Akbar May 15 '13 at 06:57
  • Is is difficult to analyze that problem without seeing the actual data/bytes. Perhaps you can NSLog() the data, locate this part in the hex output and and show it? – Martin R May 15 '13 at 07:11

2 Answers2

2

I agree, that there is an encoding problem as already said.

Referring to RFC 4627, chapter 1, a JSON string "[…]is a sequence of zero or more Unicode characters […]". Referring to RFC 4627, chapter 3, "JSON text SHALL be encoded in Unicode. The default encoding is UTF-8." What you get, is probably no unicode. (Please check this first.)

You have several options to handle that:

a) Print out RFC 4627 on thick paper. Go to the person, who is responsible for sending out this response and knock with the paper on his head until he says "I will respect RFC 4627." (This is one of the rare cases, in which violence is a solution.)

b) If you know the used encoding, create a string out of the data and then re-encode it to unicode. Scan then the encoded data with NSJSONSerializer.

c) Replace occurences of bad codes manually.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
1

Eleminating junk characters from JSON object https://gist.github.com/oleganza/781772

Akbar
  • 1,509
  • 1
  • 16
  • 32