json 如何在Swift中解析分组嵌套字典

i5desfxk  于 2023-08-08  发布在  Swift
关注(0)|答案(1)|浏览(116)

我试图在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))
                    }
                }

字符串
用户数据打印为nil。我该怎么解决呢?

zhte4eai

zhte4eai1#

我在playground中尝试了下面的代码,它工作起来很有魅力,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"))))

相关问题