【问题标题】:How to parse grouped nested dictionary in swift如何在swift中解析分组嵌套字典
【发布时间】:2020-04-14 12:36:23
【问题描述】:

请帮助我在 SWIFT5 中解析以下 json 响应,因为我正在获取用户和组数据的 nil 值。

{
    "user": {
        "0": {
            "id": "5",
            "name": "ABC"
        }
    },
    "group": {
        "0": {
            "id": "510",
            "name": "XYZ"
        }
    }
}


if let unwrappedData = data {

                    do{
                        let json = try JSONSerialization.jsonObject(with: unwrappedData, options: [])
                        print(json)

                        if let user = try? JSONDecoder().decode(UserModel.self,from:unwrappedData){
                            completion(.success(user))

                        }else{
                            let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: unwrappedData)
                            completion(.failure(errorResponse.errorValue))
                        }
                    }catch{
                        completion(.failure(error))
                    }
                }

用户数据打印为零。请帮我解决问题。

【问题讨论】:

    标签: ios json swift5 jsonparser


    【解决方案1】:

    我在操场上尝试了下面的代码,它就像魅力一样,json 有什么问题?

    数据模型

    // MARK: - Sample
    struct Sample: Codable {
        let user, group: Group
    }
    
    // MARK: - Group
    struct Group: Codable {
        let the0: The0
    
        enum CodingKeys: String, CodingKey {
            case the0 = "0"
        }
    }
    
    // MARK: - The0
    struct The0: Codable {
        let id, name: String
    }
    

    Json 数据

    let jsonData = """
    {
        "user": {
            "0": {
                "id": "5",
                "name": "ABC"
            }
        },
        "group": {
            "0": {
                "id": "510",
                "name": "XYZ"
            }
        }
    }
    """.data(using: .utf8)
    

    Json 解析

    if let data = jsonData {
            let object = try? JSONDecoder().decode(Sample.self, from: data)
            print("Json Object", object)
    }
    else {
        print("Bad Json")
    }
    

    输出

    Json Object Optional(SwiftPlayground.Sample(user: SwiftPlayground.Group(the0: SwiftPlayground.The0(id: "5", name: "ABC")), group: SwiftPlayground.Group(the0: SwiftPlayground.The0(id: "510", name: "XYZ"))))
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2018-09-05
      • 2021-10-25
      • 1970-01-01
      相关资源
      最近更新 更多