下面嵌套的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"]
}
}
使用可解码协议,您可以在修复字典字符串后手动解码它们。
据我所知,它们都具有相同的结构,因此我们只需要为所有结构定义一组结构
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