Saltar al contenido

Cómo convertir un JSON string a un diccionario?

Recabamos por diferentes espacios para traerte la solución a tu dilema, si continúas con inquietudes puedes dejar tu inquietud y contestamos con mucho gusto.

Solución:

Advertencia: este es un método conveniente para convertir un JSON string a un diccionario si, por alguna razón, tiene que trabajar desde un JSON string. Pero si tienes el JSON datos disponibles, en su lugar debe trabajar con los datos, sin utilizar un string en absoluto.

rápido 3

func convertToDictionary(text: String) -> [String: Any]? 
    if let data = text.data(using: .utf8) 
        do 
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
         catch 
            print(error.localizedDescription)
        
    
    return nil


let str = ""name":"James""

let dict = convertToDictionary(text: str)

rápido 2

func convertStringToDictionary(text: String) -> [String:AnyObject]? 
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) 
        do 
            return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
         catch let error as NSError 
            print(error)
        
    
    return nil


let str = ""name":"James""

let result = convertStringToDictionary(str)

Respuesta original de Swift 1:

func convertStringToDictionary(text: String) -> [String:String]? 
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) 
        var error: NSError?
        let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
        if error != nil 
            println(error)
        
        return json
    
    return nil


let str = ""name":"James""

let result = convertStringToDictionary(str) // ["name": "James"]

if let name = result?["name"]  // The `?` is here because our `convertStringToDictionary` function returns an Optional
    println(name) // "James"

En su versión, no pasó los parámetros adecuados para NSJSONSerialization y se olvidó de emitir el resultado. Además, es mejor verificar el posible error. Última nota: esto funciona solo si su valor es una cadena. Si pudiera ser de otro tipo, sería mejor declarar la conversión de diccionario así:

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]

y, por supuesto, también necesitaría cambiar el tipo de devolución de la función:

func convertStringToDictionary(text: String) -> [String:AnyObject]?  ... 

He actualizado la respuesta de Eric D para rápido 5:

 func convertStringToDictionary(text: String) -> [String:AnyObject]? 
    if let data = text.data(using: .utf8) 
        do 
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
            return json
         catch 
            print("Something went wrong")
        
    
    return nil

rápido 3:

if let data = text.data(using: String.Encoding.utf8) 
    do 
        let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
        print(json)
     catch 
        print("Something went wrong")
    

Recuerda dar visibilidad a esta reseña si te ayudó.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *