Вложенные (тройные) словари ObjectMapper - PullRequest
0 голосов
/ 08 марта 2019

вложенный пакет Json ниже

Проблема в том, что он преобразовывает объекты словаря json в строки, а не в правильное значение. Я не понимаю, как получить значение mvc как int, исчерпание как массив.

enter image description here

Хотите понять, как работать с гнездом

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

    }

}

1 Ответ

0 голосов
/ 08 марта 2019

Используя протокол Decodable, вы можете вручную декодировать строки словаря, как только вы их исправите.

Насколько я вижу, все они имеют одинаковую структуру, поэтому нам нужно определить только один набор структур для всех

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
...