0

我需要在 swift 4 中使用可编码来解析二维数组,请告诉我该怎么做。以下是我的代码剪断

var exclusive = “””
{“list”:[[{“primary_key”:”1",”foreign_key”:”3"},{“primary_key”:”2",”foreign_key”:”10"}],[{“primary_key”:”2",”foreign_key”:”10"},{“primary_key”:”3",”foreign_key”:”22"}]]}
“””

let exeString = try! exclusive.data(using: .utf8)

struct ListStruct : Codable {

struct listStruct :Codable {
 let primary_key : Int
 let foreign_key : Int
 }

 let list = [[listStruct]] ()
 or
 let list = [][listStruct]

}

let listofData = try! JSONDecoder().decode(ListStruct.self, from: exeString!)
4

2 回答 2

3

存在三个基本问题

  • primary_key和的值foreign_key是字符串,而不是Int。有一个简单的规则:用双引号括起来的每个 JSON 值都是 string, even "1"or "false"

  • 有一个根对象,它是一个包含一个键的字典list

  • data(using:ofStringthrow这样标记try是错误的。


此代码使用 Swift 命名约定,camelCased和小写的变量名和大写的结构名

let exeString = """
{"list":[[{"primary_key":"1","foreign_key":"3"},{"primary_key":"2","foreign_key":"10"}],[{"primary_key":"2","foreign_key":"10"},{"primary_key":"3","foreign_key":"22"}]]}
"""

struct Root : Decodable {
    let list : [[ListStruct]]
}

struct ListStruct :Codable {

    private enum CodingKeys : String, CodingKey {
        case primaryKey = "primary_key"
        case foreignKey = "foreign_key"
    }

    let primaryKey : String
    let foreignKey : String
}

do {
    let data = Data(exeString.utf8)
    let result = try JSONDecoder().decode(Root.self, from: data)
    print(result.list)
} catch { print(error) }
于 2017-12-25T09:32:23.327 回答
0

看到这个

struct Language: Codable {
var name: String
var version: Int
}

let swift = Language(name: "Swift", version: 4)
let encoder = JSONEncoder()    

if let encoded = try? encoder.encode(swift) {
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}

let decoder = JSONDecoder()
 if let decoded = try? decoder.decode(Language.self, from: encoded) {
 print(decoded.name)
}
}
于 2017-12-25T08:49:10.903 回答