gpt4 book ai didi

json - 在 Swift 上使用 Argo 解析 JSON

转载 作者:行者123 更新时间:2023-11-30 13:54:37 26 4
gpt4 key购买 nike

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

[“1”、“字符串”、“”、“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 数据的正确方法是什么?

最佳答案

供您引用:

 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)

关于json - 在 Swift 上使用 Argo 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33797957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com