下面的嵌套Json包
希望了解如何使用nest
{
"id": 16,
"user_id": 6,
"name": 4,
"med_gastro": "{'left': {'mvc': 0, 'effeciency_score': 0, 'exhaustion': [0, 0, 0]}, 'right': {'mvc': 0, 'effeciency_score': 0, 'exhaustion': [0, 0, 0]}}",
"lat_gastro": "{'left': {'mvc': 0, 'effeciency_score': 0, 'exhaustion': [0, 0, 0]}, 'right': {'mvc': 0, 'effeciency_score': 0, 'exhaustion': [0, 0, 0]}}",
"tib_anterior": "{'left': {'mvc': '13816.0', 'effeciency_score': 20.804231942965192, 'exhaustion': {'maxEffeciency': 10.16597510373444, 'subMaxEffeciency': 3.2009484291641965, 'minEffeciency': 86.63307646710136}, 'effeciency': 20.804231942965192}, 'right': {'mvc': '13816.0', 'effeciency_score': 0, 'exhaustion': [0, 0, 0]}}",
"peroneals": "{'left': {'mvc': 0, 'effeciency_score': 0, 'exhaustion': [0, 0, 0]}, 'right': {'mvc': 0, 'effeciency_score': 0, 'exhaustion': [0, 0, 0]}}"
}
编码对象
import Foundation
import ObjectMapper
class PlayerProfile : NSObject, NSCoding, Mappable{
var id : Int?
var latGastro : String?
var medGastro : String?
var name : Int?
var peroneals : String?
var tibAnterior : String?
var userId : Int?
class func newInstance(map: Map) -> Mappable?{
return PlayerProfile()
}
required init?(map: Map){}
private override init(){}
func mapping(map: Map)
{
id <- map["id"]
latGastro <- map["lat_gastro"]
medGastro <- map["med_gastro"]
name <- map["name"]
peroneals <- map["peroneals"]
tibAnterior <- map["tib_anterior"]
userId <- map["user_id"]
}
}
答案 0 :(得分:0)
使用可解码协议,您可以在修复字典字符串后手动对其进行解码。
据我所知,它们都具有相同的结构,所以我们只需要为全部定义一组结构
struct DictionaryData: Codable {
let itemLeft: Item
let itemRight: Item?
enum CodingKeys: String, CodingKey {
case itemLeft = "left"
case itemRight = "right"
}
}
struct Item: Codable {
let mvc, effeciencyScore: Int
let exhaustion: [Int]
enum CodingKeys: String, CodingKey {
case mvc
case effeciencyScore = "effeciency_score"
case exhaustion
}
}
首先,我们需要修复字符串(假设我们有PlayerProfile对象,但是当然可以在类内部完成),然后可以对字符串进行解码。
let decoder = JSONDecoder()
if let medGastro = playerProfile.medGastro, let data = medGastro.data(using: .utf8) {
let fixedString = medGastro.replacingOccurrences(of: "'", with: "\"")
do {
let jsonDict = try decoder.decode(DictionaryData.self, from: data)
// Do something with jsonDict
} catch {
print(error)
}
}
与其他字段相同,当然,因为所有字段都相同,因此您可以将其放在类似函数中
func parseString(_ string: String?) throws -> DictionaryData