首页 > 解决方案 > ObjectMapper 嵌套(三重)字典

问题描述

下面嵌套的 Json 包

问题在于它将 json 字典对象转换为字符串,而不是正确的值。我不明白如何将 mvc 值作为 int 获取,将耗尽作为数组获取。

在此处输入图像描述

想了解如何使用巢

{
        "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"]

    }

}

标签: swiftxcodeobjectmapper

解决方案


使用可解码协议,您可以在修复字典字符串后手动解码它们。

据我所见,它们都具有相同的结构,所以我们只需要为所有定义一组结构

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

推荐阅读