Pregunta

Estoy usando JSONKIT para analizar la cadena JSON en NSDictionary:

NSDictionary *deserializedData = [jsonString objectFromJSONString];

Mi pregunta es: ¿Cómo puedo cambiar los valores del diccionario y obtener una cadena JSON cambiada?

He intentado cambiar los valores del diccionario:

[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:@"ratings"];   

Pero la aplicación se bloquea en esa línea. ¿Qué estoy haciendo mal?

¡Gracias por adelantado!

¿Fue útil?

Solución

Mientras que las otras respuestas son correctas, lo que Realmente quiero En este caso es:

NSMutableDictionary *deserializedData = [jsonString mutableObjectFromJSONString];

los mutableObjectFromJSONString El método creará un diccionario mutable directamente, que ahorra tiempo y memoria.

Otros consejos

NSDictionary es un diccionario inmutable, necesitas NSMutableDictionary Para cambiar los datos. No estoy seguro de JSONKIT, pero el Parser de Cocoa JSON incorporado tiene una bandera para devolver los datos en contenedores mutables.

En el peor de los casos, puedes hacer algo así:

NSMutableDictionary* data = [NSMutableDictionary dictionaryWithDictionary:[jsonString objectFromJSONString]];
[data setObject:[NSNumber numberWithInt:iRatings] forKey:@"ratings"];
// 
// we begin with our string in json format
//
NSString *jsonString = [[NSString alloc] initWithString:@"{\"1\":\"Hole 1: Rossy Robinson - $25\",\"2\":\"Hole 7: Davey Ambrose - $25\",\"3\":\"Hole 14: Ross Robinson - $25\"}"];

//
// convert the json string to an NSMutableDictionary
//
NSError *e;
NSMutableDictionary *JSONdic = [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];

//
// change a value and add a new value in the dict
//
NSLog(@"before: object for key 1 is: %@", [JSONdic objectForKey:@"1"]);
[JSONdic setObject:@"xxx" forKey:@"1"];
[JSONdic setObject:@"Phil McQuitty" forKey:@"2"];

//
//convert dictionary object to json data
//
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&e];

//
// convert the json data back to a string
//
NSString *jsonText = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];\

//
// print out the final results
//
NSLog(@"back to string: %@", jsonText);

Intentas cambiar un IMMUTABLEOBject.

NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];

Este es un diccionario mutable y puede cambiar los valores en él.

Intentas así:

NSMutableDictionary *deserializedData = [NSMutableDictionary dictionaryWithDictionary: [jsonString objectFromJSONString]];

y luego cambiar los valores:

[deserializedData setObject:[NSNumber numberWithInt:iRatings] forKey:@"ratings"];   

Para NSDictionary No podemos agregar o cambiar los valores, por eso la aplicación se está bloqueando.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top