0

I need to parser two dimensional array using codable in swift 4,please let me how to do it. following is my code snipped

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!)
vadian
  • 274,689
  • 30
  • 353
  • 361
user2068378
  • 114
  • 7

2 Answers2

3

There are three basic issues

  • The values for primary_key and foreign_key are String, not Int. There is a simple rule: Every JSON value wrapped in double quotes is string, even "1" or "false".

  • There is a root object which is a dictionary containing one key list.

  • data(using: of String does not throw so marking with try is wrong.


This code uses the Swift naming convention, camelCased and lowercased variable names and uppercased struct names

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) }
vadian
  • 274,689
  • 30
  • 353
  • 361
0

see this

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)
}
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87