En mi aplicación iOS 5, tengo un NSString
que contiene una cadena JSON. Me gustaría deserializar esa representación de cadena JSON en un objeto NSDictionary
nativo.
"{\"password\" : \"1234\", \"user\" : \"andreas\"}"
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:@"{\"2\":\"3\"}" options:NSJSONReadingMutableContainers error:&e];
-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c'
Parece que está pasando un parámetro NSString
donde debería pasar un parámetro NSData
:
NSError *jsonError; NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Por ejemplo, tiene un NSString
con caracteres especiales en NSString
strChangetoJSON. Luego puede convertir esa cadena en respuesta JSON usando el código anterior.
Creé una categoría de la respuesta de @Abizern
@implementation NSString (Extensions) - (NSDictionary *) json_StringToDictionary { NSError *error; NSData *objectData = [self dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&error]; return (!json ? nil : json); } @end
Úselo así,
NSString *jsonString = @"{\"2\":\"3\"}"; NSLog(@"%@",[jsonString json_StringToDictionary]);
Con Swift 3 y Swift 4, String
tiene un método llamado data(using:allowLossyConversion:)
. data(using:allowLossyConversion:)
tiene la siguiente statement:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Devuelve un Dato que contiene una representación de la Cadena codificada usando una encoding dada.
Con Swift 4, los data(using:allowLossyConversion:)
String
data(using:allowLossyConversion:)
se pueden usar junto con la decode(_:from:)
JSONDecoder
decode(_:from:)
para deserializar una cadena JSON en un diccionario.
Además, con Swift 3 y Swift 4, los data(using:allowLossyConversion:)
String
data(using:allowLossyConversion:)
también se pueden usar junto con el jsonObject(with:options:)
data(using:allowLossyConversion:)
para deserializar una cadena JSON en un diccionario .
Con Swift 4, JSONDecoder
tiene un método llamado decode(_:from:)
. decode(_:from:)
tiene la siguiente statement:
func decode(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Decodifica un valor de nivel superior del tipo dado a partir de la representación JSON dada.
El código de Playground a continuación muestra cómo usar los data(using:allowLossyConversion:)
y decode(_:from:)
para obtener un Dictionary
de una String
formato JSON:
let jsonString = """ {"password" : "1234", "user" : "andreas"} """ if let data = jsonString.data(using: String.Encoding.utf8) { do { let decoder = JSONDecoder() let jsonDictionary = try decoder.decode(Dictionary.self, from: data) print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"] } catch { // Handle error print(error) } }
Con Swift 3 y Swift 4, JSONSerialization
tiene un método llamado jsonObject(with:options:)
JSONSerialization
. jsonObject(with:options:)
tiene la siguiente statement:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Devuelve un objeto Foundation a partir de datos JSON dados.
El código de Playground a continuación muestra cómo usar los data(using:allowLossyConversion:)
y jsonObject(with:options:)
data(using:allowLossyConversion:)
para obtener un Dictionary
desde una String
formato JSON:
import Foundation let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}" if let data = jsonString.data(using: String.Encoding.utf8) { do { let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String] print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"]) } catch { // Handle error print(error) } }
Usando el código de Abizern para swift 2.2
let objectData = responseString!.dataUsingEncoding(NSUTF8StringEncoding) let json = try NSJSONSerialization.JSONObjectWithData(objectData!, options: NSJSONReadingOptions.MutableContainers)