肇鑫的技术博客

业精于勤,荒于嬉

JSON转Model的一些技巧

当JSON文件存在字典时,需要为字典的value创建单独的容器。比如:

{
  "pets": {
    "dog": {
      "name": "Bark",
      "color": "Black"
    },
    "cat": {
      "name": "Miao",
      "color": "White",
      "habit": "play papers"
    }
  }
}

对应的Model应该是

struct Model: Codable {
  var pets: [String: PetContainer]
}

struct PetContainer: Codable {
  var name: String
  var color: String
  var habit: String?
}

增加一层

{
  "animals": {
    "pets": {
      "dog": {
        "name": "Bark",
        "color": "Black"
      },
      "cat": {
        "name": "Miao",
        "color": "White",
        "habit": "play papers"
      }
    }
  }
}

对应model:

struct Animal: Codable {
  var animals: [String: [String: PetContainer]]
}

再增加一层

{
  "object": {
    "animals": {
      "pets": {
        "dog": {
          "name": "Bark",
          "color": "Black"
        },
        "cat": {
          "name": "Miao",
          "color": "White",
          "habit": "play papers"
        }
      }
    }
  }
}

对应model:

struct MyObject: Codable {
  var object: [String: PetsContainer]
}

struct PetsContainer: Codable {
  var pets: [String: PetContainer]
}