4

我正在用 Gloss 替换 SwifyJSON 库。我在将 WS 响应转换为 JSON 格式时遇到问题。在 SwiftyJSON 中,我是这样做的:

guard let data = response.result.value else  {
            ...
            return
        }

let jsonData = JSON(data)

我的回复如下所示:

[{
  "lat": "45.2",
  "lon": "-79.38333",
  "name": "Sample"
}, {
  "lat": "23.43",
  "lon": "45.3",
  "name": "Sample"
}]

我需要从中创建一个 JSON 对象 ([JSON]) 数组,以便可以在此方法中使用:

let jsonArray = ?
guard let destinations = [Destination].fromJSONArray(jsonArray) else
{
    ...
    return
}

我试过了:

guard let data = response.result.value as? [(String,AnyObject)] else  {
            ...
            return
}

guard let data = response.result.value as? [Gloss.JSON] else  {
            ...
            return
}

第一个说:无法将类型“[(String,AnyObject)]”的值转换为预期的参数类型“[JSON]”第二个:条件绑定的初始化程序必须具有可选类型,而不是“[Destination]”

4

2 回答 2

1

对于问题中完全相同的“第一”和“第二”错误消息,我遇到了完全相同的问题。贝娄是我如何解决它的摘录:

import Gloss
import Alamofire

...

Alamofire.request(.GET, url, parameters: params).responseJSON {
    response in switch response.result {
    case .Success(let json):
        // Here, stations is already an array of Station class
        let stations = [Station].fromJSONArray(json as! [Gloss.JSON])
        ...
    ...
}

这是我的 Station 类的样子:

import Gloss

class Station: Decodable {
    var id: Int = 0
    var attribute1: Int = 0
    var attribute2: Int = 0

    init(id: Int, attribute1: Int, attribute2: Int) {
        super.init()
        self.id = id
        self.attribute1 = attribute1
        self.attribute2 = attribute2
    }

    required init?(json: JSON) {
        super.init()
        self.id = ("id" <~~ json)!
        self.attribute1 = ("attribute1" <~~ json)!
        self.attribute2 = ("attribute2" <~~ json)!
    }
}
于 2016-08-28T21:11:39.003 回答
0

Alamofire + Gloss 为您完成工作。

遵循文档(特别是这里),我在我的一个项目中做到了这一点(简化以消除干扰):

//iOS 9.3, Xcode 7.3

/// stripped-down version
struct Event: Decodable {
    var id: String?

    init?(json: JSON) {
    id = "id" <~~ json
    }
}

//...

func getEvents(completion: (AnyObject?) -> Void) {
    request(.GET, baseURL + endpointURL)
        .responseJSON { response in
            switch response.result {
            case .Failure(let error):
                print(error.localizedDescription)
            case .Success:
                guard let value = response.result.value as? JSON,
                let eventsArrayJSON = value["events"] as? [JSON] //Thus spake the particular API's docs
                else { fatalError() }
                let events = [Event].fromJSONArray(eventsArrayJSON)

                // do stuff with my new 'events' array of type [Events]
            }
        }
}

tl;博士

神奇之处在于将 Gloss 的fromJSONArray[1] 与 Alamofire 的.responseJSON序列化器 [2] 结合起来。

[1]init?(json: JSON)Decodable协议中均由 支持。

[2] 吐出一个 Gloss-y类型的JSON对象,又名[String : AnyObject]-type。

希望这可以帮助。:)

还可以看看这个新的 cocoapod:Alamofire-Gloss

于 2016-07-14T03:58:32.563 回答