Swift 4使用Codable解码json

时间:2017-09-16 05:35:39

标签: swift4 codable

有人可以告诉我我做错了什么吗?我已经在这里查看了所有问题,例如How to decode a nested JSON struct with Swift Decodable protocol?,我发现了一个看起来正是我需要的问题Swift 4 Codable decoding json

setAdapter

我得到的错误是:

  

typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:   [],debugDescription:"预计解码数组但发现了一个   而不是字典。",underlyingError:nil))

3 个答案:

答案 0 :(得分:8)

检查JSON文本的概述结构:

{
    "success": true,
    "message": "got the locations!",
    "data": {
      ...
    }
}

"data"的值是JSON对象{...},它不是数组。 和对象的结构:

{
    "LocationList": [
      ...
    ]
}

该对象只有一个条目"LocationList": [...],其值为数组[...]

您可能还需要一个结构:

struct Location: Codable {
    var data: LocationData
}

struct LocationData: Codable {
    var LocationList: [LocationItem]
}

struct LocationItem: Codable {
    var LocID: Int!
    var LocName: String!
}

进行测试......

var jsonText = """
{
    "success": true,
    "message": "got the locations!",
    "data": {
        "LocationList": [
            {
                "LocID": 1,
                "LocName": "Downtown"
            },
            {
                "LocID": 2,
                "LocName": "Uptown"
            },
            {
                "LocID": 3,
                "LocName": "Midtown"
            }
        ]
    }
}
"""

let data = jsonText.data(using: .utf8)!
do {
    let locList = try JSONDecoder().decode(Location.self, from: data)
    print(locList)
} catch let error {
    print(error)
}

答案 1 :(得分:0)

在搜索了很多东西之后,我当然确定这是从任何对象中打印格式正确的json的最甜蜜的方式。

let jsonString = object.toJSONString(prettyPrint: true)
print(jsonString as AnyObject)

答案 2 :(得分:0)

有关JSONEncoder的Apple文档->

struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)

/* Prints:
 {
   "name" : "Pear",
   "points" : 250,
   "description" : "A ripe pear."
 }
*/