使用Gloss反序列化数组

时间:2017-04-10 08:53:35

标签: json swift

Gloss library使得在Swift中处理JSON变得更加容易。但是,有一个用例我无法在文档中找到。假设您有一个包含对象数组的键:

{
    "id" : 40102424,
    "name": "Gloss",
    "description" : "A shiny JSON parsing library in Swift",
    "html_url" : "https://github.com/hkellaway/Gloss",
    "people" : [
        {
            "id" : 5456481,
            "login" : "hkellaway1"
        },
        {
            "id" : 5456482,
            "login" : "hkellaway2"
        },
        {
            "id" : 5456483,
            "login" : "hkellaway3"
        }
    ]
    "language" : "Swift"
}

尝试像这样初始化会产生错误:

let people : Array<People>?
required init?(json: JSON)
{
    // Error: Value of optional type '[JSON]?' not unwrapped; did you mean to use '!' or '?'?
    self.people = [People].from(jsonArray: "people" <~~ json)
}

我应该为“来自”功能传递什么?强行解开json可能会导致崩溃。

编辑:

使用保护声明有效,但&#34;人员&#34;密钥可能包含也可能不包含或者没有对象。在这种情况下,以下代码将为整个对象返回nil:

guard let jarr: [JSON] = "" <~~ json else {
   return nil
}
self.people = [People].from(jsonArray: jarr)

使用if let会给我一个错误:

let people : Array<People>?

// Error: Property 'self.people' not initialized at implicitly generated super.init call
required init?(json:JSON)
{
   if let jarr : [JSON] = "people" <~~ json {
      self.people = [People].from(jsonArray: jarr)
   }
}

1 个答案:

答案 0 :(得分:1)

尝试在创建数组之前从json中解开people数组。 init方法是可以使用的,因此如果您返回nil并不重要。

let people: Array<People>?
required init?(json: JSON) {
    guard let people: [JSON] = "people" <~~ json, else {
        return nil
    }
    self.people = [People].from(people)
}

编辑:

let people: [People] = []
required init?(json: JSON) {
    if let peopleJSON: [JSON] = "people" <~~ json,
        let people = [People].from(people) {
        self.people = people
    }
}

这种方式people始终至少是一个空数组,如果有人要添加,则会添加它们。