2010-11-14 6 views
2

Je reçois une chaîne JSON invalide, qui contient; . (Caractères Tout deviner ce qui se passeUne chaîne JSON non valide

Mon code:

-(void)getJSONFeed { 
    // Create the URL & Request  
NSURL *feedURL = [NSURL URLWithString:  
    @"http://maps.googleapis.com/maps/api/geocode/json?  address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true"];  
NSURLRequest *request = [NSURLRequest requestWithURL:feedURL]; 
// Example connection only. Add Timeouts, cachingPolicy in production 
[NSURLConnection connectionWithRequest:request delegate:self ]; 
// init the jsonData Property 
jsonData = [[NSMutableData data] retain]; 
} 

// NSURLConnection Delegate Methods. You would want to include more for error handling // 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data { 
NSLog(@"Recieving Data..."); 
// Append the incomming data as it is received 
[jsonData appendData:data]; 
NSLog(@"%@",jsonData); 
} 

-(NSDictionary *)parseJSON:(NSMutableData *)data { 
NSLog(@"Parsing JSON");  
NSError *error = nil; 
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error]; 
return dictionary; 
} 

// Parse JSON results with TouchJSON. It converts it into a dictionary. 


-(void)connectionDidFinishLoading:(NSURLConnection *)connection { 
NSLog(@"Fininshed Loading..."); 
NSDictionary * feedDictionary = [self parseJSON:jsonData]; 
NSLog(@"JSON as NSDictionary: %@", feedDictionary); 
} 

{ 
    results =  (
       { 
      "address_components" =    (
           { 
        "long_name" = 1600; 
        "short_name" = 1600; 
        types =      (
         "street_number" 
        ); 
       }, 
           { 
        "long_name" = "Amphitheatre Pkwy"; 
        "short_name" = "Amphitheatre Pkwy"; 
        types =      (
         route 
        ); 
       }, 
           { 
        "long_name" = "Mountain View"; 
        "short_name" = "Mountain View"; 
        types =      (
         locality, 
         political 
        ); 
       }, 
           { 
        "long_name" = "San Jose"; 
        "short_name" = "San Jose"; 
        types =      (
         "administrative_area_level_3", 
         political 
        ); 
       }, 
           { 
        "long_name" = "Santa Clara"; 
        "short_name" = "Santa Clara"; 
        types =      (
         "administrative_area_level_2", 
         political 
        ); 
       }, 
           { 
        "long_name" = California; 
        "short_name" = CA; 
        types =      (
         "administrative_area_level_1", 
         political 
        ); 
       }, 
           { 
        "long_name" = "United States"; 
        "short_name" = US; 
        types =      (
         country, 
         political 
        ); 
       }, 
           { 
        "long_name" = 94043; 
        "short_name" = 94043; 
        types =      (
         "postal_code" 
        ); 
       } 
      ); 
      "formatted_address" = "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"; 
      geometry =    { 
       location =     { 
        lat = "37.422782"; 
        lng = "-122.085099"; 
       }; 
       "location_type" = ROOFTOP; 
       viewport =     { 
        northeast =      { 
         lat = "37.4259296"; 
         lng = "-122.0819514"; 
        }; 
        southwest =      { 
         lat = "37.4196344"; 
         lng = "-122.0882466"; 
        }; 
       }; 
      }; 
      types =    (
       "street_address" 
      ); 
     } 
    ); 
    status = OK; 
} 

MISE À JOUR:

D'une certaine manière, il l'interprète comme une liste de propriétés Le format semble être similaire à. le format NeXTSTEP original avec =;

Répondre

0

Je ne suis pas sûr à 100% quelle est la question.Vous faites une connexion HTTP valide, qui fait une demande significative de Google (si vous supprimer les six espaces au milieu qui sont presque certainement le résultat de la copie de code et coller ici). Vous accumulez le résultat. Dans le code donné, vous semblez fuir l'objet jsonData, mais je suppose que cela n'a aucun rapport avec la question.

Vous utilisez l'objet CJSONDeserializer dont je n'ai pas entendu parler mais qui semble être souvent mentionné sur Google, donc probablement digne de confiance. Il renvoie un NSDictionary valide. Vous imprimez le dictionnaire et il contient les résultats corrects.

La confusion est-elle juste que lorsque vous imprimez le dictionnaire sur la console, il ne semble pas identique au JSON que vous avez reçu? Si c'est le cas, c'est parce qu'il n'a plus aucun concept qui vient de JSON et que Cocoa est antérieur au standard JSON et ne l'utilise donc pas pour la journalisation.

Dans tous les cas, feedDictionary est un dictionnaire valide. Ce qui suit:

NSLog(@"%@", [feedDictionary objectForKey:@"status"]); 

Imprime la chaîne 'OK'. Ce:

NSArray *addressComponents = [feedDictionary objectForKey:@"address_components"]; 
for(NSDictionary *component in addressComponents) 
{ 
    NSLog(@"%@", [component objectForKey:@"long_name"]); 
} 

imprimerait les cordes '1600', 'Amphitheatre Pkwy', 'Mountain View', 'San Jose', 'Santa Clara', 'Californie', 'États-Unis', '94043' en cet ordre.

Si vous souhaitez imprimer la première JSON à la console, vous voulez probablement quelque chose comme ceci (en supposant que le résultat revient en UTF8):

-(void)connectionDidFinishLoading:(NSURLConnection *)connection { 
NSLog(@"Fininshed Loading..."); 

NSString *feedString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
NSLog(@"JSON was: %@", feedString); 
[feedString release]; 

/*NSDictionary * feedDictionary = [self parseJSON:jsonData]; 
NSLog(@"JSON as NSDictionary: %@", feedDictionary); */ 
} 

Bien que vous aurez besoin encore d'analyser à un dictionnaire pour en obtenir des résultats significatifs.

+0

Merci Tommy! Vous avez déjà répondu à ma question. J'ai été confus par l'impression de NSLog, mais en fait, comme vous l'avez souligné si vous utilisez NSUTF8StringEncoding, vous obtenez une impression json valide. J'ai juste dû faire face aux touches 'state' et 'results' et votre solution fonctionne: NSArray * results = [feedDictionary objectForKey: @ "results"]; NSArray * addressComponents = [[objet de résultat objectAtex: 0] objectForKey: @ "address_components"]; \t pour (composant NSDictionary * dans addressComponents) { \t \t NSLog (@ "% @", [component objectForKey: @ "long_name"]); \t} – Zsolt