在Swift上使用Argo解析JSON

时间:2015-11-19 07:48:15

标签: json swift parsing

我正在尝试使用下一种格式解析JSON数据:

["1", "string", "", "0.16"]

这些“奇怪的”json应该以下一个方式映射到我的对象:

myObject.id = json[0] //"1"
myObject.name = json[1] //"string"
myObject.surname = json[2] // ""
myObject.length = json[3] // "0.16"

我正在使用Argo进行解析,还有我的代码示例

public struct SomeObject {
     public var id: String
     public var name: String
     public var surname: String
     public var length: Float
}

extension SomeObject: Decodable {
    static func create(id: String)(name: String)(surname: String)(length: String) -> SomeObject {
         return SomeObject(id: id, name: name, surname: surname, length: length)
}

    public static func decode(json: JSON) -> Decoded<SomeObject> {
         return SomeObject.create <- actually don't know what to put here, i tried json[0], and decode(json[0]) and casting but still no luck
}

解析那种JSON数据的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

供您参考:

 let ar = ["1", "string", "", "0.16"]

public struct SomeObject {
    public var id: String?
    public var name: String?
    public var surname: String?
    public var length: Float?
}

extension SomeObject {
    static func create(id: String?, name: String?, surname: String?, length: Float?) -> SomeObject {
        return SomeObject(id: id, name: name, surname: surname, length: length)
    }

    public static func decode(json: AnyObject?) -> SomeObject {
        let js = json as! Array<AnyObject>
        return SomeObject.create(js[0] as? String, name: js[1] as? String, surname: js[2] as? String, length: js[3] as? Float)
    }
}

let someObject = SomeObject.decode(ar)

答案 1 :(得分:0)

Argo没有设置从这样的数组中提取某些索引。您要做的是先将其解码为[String],然后选择您想要的索引。

let values: Decoded<[String]> = decodeArray(json)
return SomeObject.create
  <^> ({ $0[0] } <^> values)
  <*> ({ $0[1] } <^> values)
  <*> ({ $0[2] } <^> values)
  <*> (values >>- { .fromOptional(Float($0[3])) })

你可以看到我使用闭包来提取所需的索引。最后一个还会将String投射到Float以匹配您的类型。

除了这个解析代码,您还可以使用let代替var来改进模型,使其不可变,并使用Curry框架(https://github.com/thoughtbot/Curry)而不是创建拥有咖喱初始化器。