-2

我有一堂课,它有下一个

import UIKit

final class PruebaModel: Codable {
    
    let a: String?
    let b: String?
    let c: [D]?
    let f: String?
    
    
    enum CodingKeys: String, CodingKey {
        case a = "a"
        case b = "b"
        case c = "c"
        case f = "f"
    }
    
    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        a = try values.decodeIfPresent(String.self, forKey: .a)
        b = try values.decodeIfPresent(String.self, forKey: .b)
        c = try values.decodeIfPresent([D].self, forKey: .c)
        f = try values.decodeIfPresent(String.self, forKey: .f)
    }
    
    required init()  {
        a = ""
        b = ""
        c = Array<D>()
        f = ""
    }
}


import Foundation

struct D: Codable {
    let l: String
    let m: String
    
    enum CodingKeys: String, CodingKey {
        case l = "l"
        case m = "m"
    }
    
    init(from decoder: Decoder) throws {
        let value = try decoder.container(keyedBy: CodingKeys.self)
        l = try value.decode(String.self, forKey: .l)
        m = try value.decode(String.self, forKey: .m)
    }
    
    public func encode(to encoder: Encoder) throws {
        //Implement when needed
    }
}

json是下一个

{
     
     "a": "a",
     "b": "b",
     "c": [
       {
         "l": "¿Cuál es el mi color favorito?",
         "m":"QAUY.15"
       }
    ],
    "f": "f"
     
}

该类是完美的,它具有带参数的对象,但是当我尝试将类转换为 json 时。数组为空

代码

let jsonData = try! JSONEncoder().encode(PruebaModel)
let jsonString = String(data: jsonData, encoding: .utf8)!

我评估表达式时的结果

po String(data: try! JSONEncoder().encode(PruebaModel), encoding: .utf8)!

"{"a":"a","b":"b","c":[{}],"f":"f"}"

为什么 c 是空的?它在数组中有一个对象。

如果对象在数组中没有特殊字符,则解码显示该对象

4

1 回答 1

0

不清楚你在问什么。一方面,你有太多的代码。另一方面,您显示的代码毫无意义。另一方面,您展示的 JSON 可以很好地解码为 PruebaModel,并且正确构造的 PruebaModel 可以编码为您的 JSON:

struct D: Codable {
    let l: String
    let m: String
}
struct PruebaModel: Codable {
    let a: String?
    let b: String?
    let c: [D]?
    let f: String?
}
let jsonString = """
{
    "a": "a",
    "b": "b",
    "c": [
        {
            "l": "¿Cuál es el mi color favorito?",
            "m":"QAUY.15"
        }
    ],
    "f": "f"
    }
"""
let jsonData = jsonString.data(using: .utf8)!
let result = try? JSONDecoder().decode(PruebaModel.self, from: jsonData)
print(result?.c?.first?.l) // Optional("¿Cuál es el mi color favorito?")
// let's also try encoding
let d = D(l: "¿Cuál es el mi color favorito?", m: "QAUY.15")
let myPruebaModel = PruebaModel(a: "a", b: "b", c: [d], f: "f")
let jsonData2 = try? JSONEncoder().encode(myPruebaModel)
print(String(data: jsonData2!, encoding: .utf8)!)
// {"b":"b","c":[{"l":"¿Cuál es el mi color favorito?","m":"QAUY.15"}],"a":"a","f":"f"}
于 2020-10-20T23:16:06.897 回答