我一直在尝试解码一个应用程序的数组,在这个应用程序中,我必须解码JSON。
我只是无法用我以前尝试过的实际结构和其他结构来破解它。
以下是我的最新结构:
struct peticion: Decodable{
let datos_conexion: datos_conexion
let estado_lanzamiento: estado_lanzamiento
let usuario: usuario
}
struct datos_conexion: Decodable {
let conexion: datosConexion
}
struct datosConexion: Decodable{
let datos_conexion: String
}
struct estado_lanzamiento: Decodable{
let tiempo_restante: String
let etapa_actual: String
}
struct usuario: Decodable {
let Id: Int
let Nombre: String
let Password: String
let Imagen: String
let Puesto: String
let Departamento: String
}
JSON请求中的完整示例
[
{
"datos_conexion": {
"conexion": "2019-05-27 17:05:45"
}
},
{
"estado_lanzamiento": {
"tiempo_restante": 240,
"etapa_actual": "Configuracion"
}
},
{
"usuario": [
{
"Id": "4",
"Nombre": "This is the Name",
"Email": "email@gmail.com",
"Password": "1234",
"Imagen": "default.jpg",
"Puesto": "",
"Departamento": "Etapa Final"
}
]
}
]
译码码
URLSession.shared.dataTask(with: url2) { (data, resp, err) in
guard let data = data else{return}
let dataAsString = String(data: data, encoding: .utf8)
// print(dataAsString)
do {
let JSONDATA = try JSONDecoder().decode([peticion].self, from: data)
// print(data)
} catch let jsonErr {
print("cant decode", jsonErr)
}
试图这样做的错误:
typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“期望解码数组,但找到了字典。”,underlyingError: 0)) typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[],debugDescription:“期望解码字典,但找到了数组。”,underlyingError: 0))
发布于 2019-05-28 01:14:47
基于您的JSON,您正在接收一个[[String: Any]]
,该Array
包含Dictionaries
of Any
值和String
键。这是一个棘手的问题,因为字典中包含的是不可解码的Any
值。另外,容器是Array
,通常我们会有一个Dictionary
作为容器。
通常情况下,我们会简化这个反应。但我们不能在这种情况下。
对此进行解码的一个方法是:
struct Peticion: Decodable{
let datosConexion: DatosConexion
let estadoLanzamiento: EstadoLanzamiento
let usuario: [Usuario]
init(from decoder : Decoder) throws {
//unkeyed because we are getting an array as container
var unkeyedContainer = try decoder.unkeyedContainer()
let datosConexionWrapper = try unkeyedContainer.decode(DatosConexionWrapper.self)
let estadoLanzamientoWrapper = try unkeyedContainer.decode(EstadoLanzamientoWrapper.self)
let usuarioWrapper = try unkeyedContainer.decode(UsuarioWrapper.self)
datosConexion = datosConexionWrapper.datosConexion
estadoLanzamiento = estadoLanzamientoWrapper.estadoLanzamiento
usuario = usuarioWrapper.usuario
}
}
//use wrappers to handle the outer dictionary
struct DatosConexionWrapper: Decodable{
let datosConexion: DatosConexion
enum CodingKeys: String, CodingKey{
case datosConexion = "datos_conexion"
}
}
struct DatosConexion: Decodable{
let conexion: String
}
struct EstadoLanzamientoWrapper: Decodable{
let estadoLanzamiento: EstadoLanzamiento
enum CodingKeys: String, CodingKey{
case estadoLanzamiento = "estado_lanzamiento"
}
}
struct EstadoLanzamiento: Decodable{
let tiempoRestante: Int
let etapaActual: String
enum CodingKeys: String, CodingKey {
case tiempoRestante = "tiempo_restante"
case etapaActual = "etapa_actual"
}
}
struct UsuarioWrapper: Decodable{
let usuario: [Usuario]
}
struct Usuario: Decodable{
let id: String
let nombre: String
let email: String
let password: String
let imagen: String
let puesto: String
let departamento: String
enum CodingKeys: String, CodingKey {
case id = "Id"
case nombre = "Nombre"
case email = "Email"
case password = "Password"
case imagen = "Imagen"
case puesto = "Puesto"
case departamento = "Departamento"
}
}
解码代码//我只将解码类型更改为我的
URLSession.shared.dataTask(with: url2) { (data, resp, err) in
guard let data = data else{return}
let dataAsString = String(data: data, encoding: .utf8)
// print(dataAsString)
do {
let JSONDATA = try JSONDecoder().decode(Peticion.self, from: data)
// print(data)
} catch let jsonErr {
print("cant decode", jsonErr)
}
这是个有趣的练习。这也是未经测试的代码,但我非常肯定它会工作。
发布于 2019-05-27 14:56:57
import Foundation
// MARK: - WelcomeElement
struct WelcomeElement: Codable {
let datosConexion: DatosConexion?
let estadoLanzamiento: EstadoLanzamiento?
let usuario: [Usuario]?
enum CodingKeys: String, CodingKey {
case datosConexion = "datos_conexion"
case estadoLanzamiento = "estado_lanzamiento"
case usuario
}
}
// MARK: - DatosConexion
struct DatosConexion: Codable {
let conexion: String
}
// MARK: - EstadoLanzamiento
struct EstadoLanzamiento: Codable {
let tiempoRestante: Int
let etapaActual: String
enum CodingKeys: String, CodingKey {
case tiempoRestante = "tiempo_restante"
case etapaActual = "etapa_actual"
}
}
// MARK: - Usuario
struct Usuario: Codable {
let id, nombre, email, password: String
let imagen, puesto, departamento: String
enum CodingKeys: String, CodingKey {
case id = "Id"
case nombre = "Nombre"
case email = "Email"
case password = "Password"
case imagen = "Imagen"
case puesto = "Puesto"
case departamento = "Departamento"
}
}
typealias Welcome = [WelcomeElement]
https://stackoverflow.com/questions/56333106
复制