ios 无法读取数据,因为它的格式不正确 [swift 3]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41875967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:06:05  来源:igfitidea点击:

The data couldn’t be read because it isn’t in the correct format [swift 3]

iosjsonswiftswift3nsdictionary

提问by Aldo Lazuardi

I've json data that have json string(value) that that look like this

我有 json 数据,其 json 字符串(值)看起来像这样

{
     "Label" : "NY Home1",
     "Value" : "{\"state\":\"NY\",\"city\":\"NY\",\"postalCode\":\"22002\",\"value\":\"Fifth Avenue1\nNY NY 22002\nUSA\",\"iosIdentifier\":\"71395A78-604F-47BE-BC3C-7F932263D397\",\"street\":\"Fifth Avenue1\",\"country\":\"USA\"}",
}

I take the jsonString using swiftyjson

我使用 swiftyjson 获取 jsonString

let value = sub["Value"].string ?? ""

After that I convert this jsonString to Dictionary with this below code but it always show this error message The data couldn't be read because it isn't in the correct format

之后,我使用以下代码将此 jsonString 转换为 Dictionary,但它始终显示此错误消息 The data couldn't be read because it isn't in the correct format

if let data = value.data(using: String.Encoding.utf8) {
        do {
            let a = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            print("check \(a)")
        } catch {
            print("ERROR \(error.localizedDescription)")
        }
    }

I think this happen because "\n", how to convert jsonstring to dictionary that have "\n" ?

我认为这是因为 "\n",如何将 jsonstring 转换为具有 "\n" 的字典?

采纳答案by EPerrin95

You're right, problem occurred because of "\n". I tried your code without "\n" and it's work perfectly.

你是对的,问题是因为“\n”而发生的。我在没有 "\n" 的情况下尝试了你的代码,它完美地工作。

I replaced "\n" by "\\n", and iOS seems to convert the string to dictionary :

我用“\\n”替换了“\n”,iOS似乎将字符串转换为字典:

let value =  "{\"state\":\"NY\",\"city\":\"NY\",\"postalCode\":\"22002\",\"value\":\"Fifth Avenue1\nNY NY 22002\nUSA\",\"iosIdentifier\":\"71395A78-604F-47BE-BC3C-7F932263D397\",\"street\":\"Fifth Avenue1\",\"country\":\"USA\"}"

if let data = value.replacingOccurrences(of: "\n", with: "\n").data(using: String.Encoding.utf8) {
    do {
       let a = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String: Any]
       NSLog("check \(a)")
    } catch {
       NSLog("ERROR \(error.localizedDescription)")
    }
}

I obtained this in my log :

我在我的日志中得到了这个:

check Optional(["value": Fifth Avenue1
NY NY 22002
USA, "country": USA, "city": NY, "iosIdentifier": 71395A78-604F-47BE-BC3C-7F932263D397, "street": Fifth Avenue1, "postalCode": 22002, "state": NY])