代码之家  ›  专栏  ›  技术社区  ›  casillas

在Swift中解码json对象

  •  -1
  • casillas  · 技术社区  · 6 年前

    我有一个json文件,读取并解码如下。 我的json文件如下所示,A和B代表struct对象。我想知道有没有更好、更有效的方法来解码这种类型的json?

    [ 
     [
       {"id": "152478", "age": "20"},{"character": "king", "isDead":"no", "canMove" :"yes"}
     ],
     [
      {"id": "887541", "age": "22"},{"character": "lion", "isDead":"no", "canMove" :"yes"}
     ]
    ]
    

    解码如下:

        let url = Bundle.main.url(forResource: "mypew", withExtension: "json")!
            do {
    
            let jsonData = try Data(contentsOf: url)
    
             // B -> json[0][0], [1][0]
             // A -> json[0][1], [0][1]
    
            response = try JSONSerialization.jsonObject(with: jsonData) as! [[[String: Any]]]
            for i in 0..<response.count
            {
                for j in 0..<response[i].count
                {
                    if j == 0
                    {
                        let jsonDat = (try? JSONSerialization.data(withJSONObject:response[i][j]))!
                        let bElement = try JSONDecoder().decode(B.self, from: jsonDat)
                        self.bArray.append(bElement)
                    }
                    else if j == 1
                    {
                        let jsonDatt = (try? JSONSerialization.data(withJSONObject:response[i][j]))!
                        let aElement = try JSONDecoder().decode(A.self, from: jsonDatt)
                        self.aArray.append(aElement)
                    }
                }
            }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   New Dev    6 年前

    首先,制作两个对象(我们称之为 A 和 B )符合 Decodable :

    struct A: Decodable {
        var id, age: String
    }
    
    struct B: Decodable {
        var character, isDead, canMove: String
    }
    

    那么,如果你的结构为 A. 和 B 都是一样的,也就是说 [A, B] ,然后你可以把这对解码成它自己的对象。我们称之为物体 ABPair :

    struct ABPair: Decodable {
      let a: A
      let b: B
    
      init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
    
        guard let a = try? container.decode(A.self), 
              let b = try? container.decode(B.self) 
          else {
            // throw since we didn't find A first, followed by B
            throw DecodingError.dataCorruptedError(in: container, debugDescription: "error")
          }
    
        self.a = a
        self.b = b
      }
    }
    

    您可以按如下方式解码成对数组:

    let decoder = JSONDecoder()
    let pairs = try? decoder.decode([ABPair].self, from: jsonData)
    
    print(pairs[1].b.character) // lion
    
        2
  •  -2
  •   Frankenstein    6 年前

    首先,你需要创建一个 Codable 模型的结构。然后从数据而不是JSON对象解码模型。这里是代码,

    型号:

    struct Model: Codable {
        let id, age, character, isDead, canMove: String?
    }
    

    解码:

    let url = Bundle.main.url(forResource: "mypew", withExtension: "json")!
    do {
        let jsonData = try Data(contentsOf: url)
        let models = try JSONDecoder().decode([[Model]].self, from: jsonData)
        for model in models {
            print(model[0].age, model[1].canMove)
        }
    } catch {
        print(error)
    }