在Swift中解码不同类型的JSON数组 [英] Decoding JSON array of different types in Swift

查看:124
本文介绍了在Swift中解码不同类型的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解码以下JSON对象

I'm trying to decode the following JSON Object

{
    "result":[
             {
             "rank":12,
             "user":{ 
                     "name":"bob","age":12 
                    } 
             }, 
             {
             "1":[ 
                  {
                    "name":"bob","age":12
                  },
                  {
                   "name":"tim","age":13
                  }, 
                  {
                   "name":"tony","age":12
                  }, 
                  {
                   "name":"greg","age":13
                  } 
                 ] 
            } 
           ] 
}

struct userObject { 变量名称:字符串 变量年龄:整数 }

struct userObject { var name: String var age: Int }

基本上是具有两种不同对象类型的JSON数组

Basically a JSON Array with two different object types

{ "rank":12, "user": {userObject} }

和一个 "1":[userObjects]

struct data: Decodable {
   rank: Int
   user: user
   1:    [user]  <-- this is one area Im stuck
}

预先感谢

推荐答案

只是为了好玩:

首先,您需要为用户提供结构,并在result数组中显示第一和第二个字典.键"1"映射到one

First you need structs for the users and the representation of the first and second dictionary in the result array. The key "1" is mapped to one

struct User : Decodable {
    let name : String
    let age : Int
}

struct FirstDictionary : Decodable {
    let rank : Int
    let user : User
}

struct SecondDictionary : Decodable {
    let one : [User]

    private enum CodingKeys: String, CodingKey { case one = "1" }
}


现在是棘手的部分:


Now comes the tricky part:

  • 首先获取根容器.
  • 因为对象是数组,所以将result的容器作为nestedUnkeyedContainer获取.
  • 解码第一个词典并复制值.
  • 解码第二个词典并复制值.

  • First get the root container.
  • Get the container for result as nestedUnkeyedContainer because the object is an array.
  • Decode the first dictionary and copy the values.
  • Decode the second dictionary and copy the values.

struct UserData: Decodable {

    let rank : Int
    let user : User
    let oneUsers : [User]

   private enum CodingKeys: String, CodingKey { case result }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        var arrayContainer = try container.nestedUnkeyedContainer(forKey: .result)
        let firstDictionary = try arrayContainer.decode(FirstDictionary.self)
        rank = firstDictionary.rank
        user = firstDictionary.user
        let secondDictionary = try arrayContainer.decode(SecondDictionary.self)
        oneUsers = secondDictionary.one
    }
}

如果此代码比传统的手册 JSONSerialization更可取,则是另一个问题.

If this code is preferable over traditional manual JSONSerialization is another question.

这篇关于在Swift中解码不同类型的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆