序列化包含转义(反斜杠和双引号)的JSON字符串Swift返回错误形成的对象

时间:2018-05-16 08:09:21

标签: ios json swift nsjsonserialization jsonserializer

我有来自后端的响应字符串,如下所示:

{
    "status": "success",
    "data": "{\"name\":\"asd\",\"address\":\"Street 1st\"}"
}

我认为问题是因为数据字符串中的双引号(“)。当我删除双引号时,序列化是成功的。但响应来自后端,我必须处理它。

任何人都可以解决这个问题吗?

谢谢。

这是游乐场代码。

import Foundation
var jsonStr = """
{
"status": "success",
"data": "{\"name\":\"asd\",\"address\":\"Street 1st\"}"
}
"""
let data = jsonStr.data(using: .utf8)
if let d = data {
    do {
        let o = try JSONSerialization.jsonObject(with: d)
        print(o)
    } catch let e {
        print(e)
    }
} else {
    print("DATA conversion ERROR")
}

3 个答案:

答案 0 :(得分:3)

首先,如果你在Swift 4的文字字符串语法中包装JSON,你必须转义反斜杠。

let jsonStr = """
{
"status": "success",
"data": "{\\"name\\":\\"asd\\",\\"address\\":\\"Street 1st\\"}"
}
"""

你有嵌套的JSON。键data的值是另一个JSON字符串,必须单独反序列化

let jsonData = Data(jsonStr.utf8)

do {
    if let object = try JSONSerialization.jsonObject(with: jsonData) as? [String:String] {
        print(object)
        if let dataString = object["data"] as? String {
            let dataStringData = Data(dataString.utf8)
            let dataObject = try JSONSerialization.jsonObject(with: dataStringData) as? [String:String]
            print(dataObject)
        }
    }
} catch {
    print(error)
}

或者 - 稍微努力但是 - 使用(De)Codable协议更加舒适

struct Response : Decodable {

    private enum CodingKeys : String, CodingKey { case status, data }

    let status : String
    let person : Person

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        status = try container.decode(String.self, forKey: .status)
        let dataString = try container.decode(String.self, forKey: .data)
        person = try JSONDecoder().decode(Person.self, from: Data(dataString.utf8))
    }
}

struct Person : Decodable {
    let name, address : String
}
let jsonStr = """
{
"status": "success",
"data": "{\\"name\\":\\"asd\\",\\"address\\":\\"Street 1st\\"}"
}
"""
let jsonData = Data(jsonStr.utf8)

do {
    let result = try JSONDecoder().decode(Response.self, from: jsonData)
    print(result)
} catch {
    print(error)
}

答案 1 :(得分:0)

您的代码中有错误,因为您在代码中写了这样的错误""" json""",

也  data String不是字典,因此您需要再次转换为数据JSONSerialization

检查代码我在Json文件中添加您的响应并解析它,并正常工作

所以只需在json文件中写一下这个名为 data.json

的文件
{
    "status": "success",
    "data": "{\"name\":\"asd\",\"address\":\"Street 1st\"}"
}

并使用此:

            guard let  jsonFile =  Bundle.main.path(forResource: "data", ofType: "json") else { return}

            guard  let data = try? Data(contentsOf: URL(fileURLWithPath: jsonFile), options: .mappedIfSafe) else {return}

            if let response  = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) {
                print(response)
                if let dataInDictionary = response as? [String:Any] , let addresData = dataInDictionary["data"] as? String {

                    if let jsonData = addresData.data(using: .utf8),
                        let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as? [String:Any]{
                        print(dictionary)
                    }
                }
            }

答案 2 :(得分:0)

这是基于答案@vadian的另一个示例

迅速4-使用可编码

这是我收到的json:

{
    "error_code": 0,
    "result": {
        "responseData": "{\"emeter\":{\"get_realtime\":{\"voltage_mv\":237846,\"current_ma\":81,\"power_mw\":7428,\"total_wh\":1920,\"err_code\":0}}}"
    }
} 

带有反斜杠的JSON部分等于:

{
    "emeter": {
        "get_realtime": {
            "voltage_mv": 237846,
            "current_ma": 81,
            "power_mw": 7428,
            "total_wh":19201,
            "err_code":0
        }
    }
}

这是我使用的代码:

import Foundation

class RealtimeEnergy: Codable {
    let errorCode: Int
    let result: ResultRealtimeEnergy?
    let msg: String?

    enum CodingKeys: String, CodingKey {
        case errorCode = "error_code"
        case result, msg
    }

    init(errorCode: Int, result: ResultRealtimeEnergy?, msg: String?) {
        self.errorCode = errorCode
        self.result = result
        self.msg = msg
    }
}

class ResultRealtimeEnergy: Codable {

    let responseData: String
    var emeter: Emeter

    enum CodingKeys: String, CodingKey {
        case responseData
    }

    required init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        responseData = try container.decode(String.self, forKey: .responseData)
        let dataString = try container.decode(String.self, forKey: .responseData)
        emeter = try JSONDecoder().decode(Emeter.self, from: Data(dataString.utf8))
    }
}



class Emeter: Codable {
    let emeter: EmeterClass

    init(emeter: EmeterClass) {
        self.emeter = emeter
    }
}

class EmeterClass: Codable {
    let getRealtime: GetRealtime

    enum CodingKeys: String, CodingKey {
        case getRealtime = "get_realtime"
    }

    init(getRealtime: GetRealtime) {
        self.getRealtime = getRealtime
    }
}

class GetRealtime: Codable {
    let voltageMv, currentMa, powerMw, totalWh: Int
    let errCode: Int

    enum CodingKeys: String, CodingKey {
        case voltageMv = "voltage_mv"
        case currentMa = "current_ma"
        case powerMw = "power_mw"
        case totalWh = "total_wh"
        case errCode = "err_code"
    }

    init(voltageMv: Int, currentMa: Int, powerMw: Int, totalWh: Int, errCode: Int) {
        self.voltageMv = voltageMv
        self.currentMa = currentMa
        self.powerMw = powerMw
        self.totalWh = totalWh
        self.errCode = errCode
    }
}