【问题标题】:Convert JSON string UTF8 to NSDictionary Swift将 JSON 字符串 UTF8 转换为 NSDictionary Swift
【发布时间】:2016-11-08 05:20:13
【问题描述】:

我想从 JSON 字符串转换为 NSDictionary 并且数据是 UTF8。 这是我的代码:

    override func viewDidLoad() {
    super.viewDidLoad()
    let string = "{\"name\":\"Việt NAM\",\"data\":{\"capital\":\"HÀ NỘI\",\"continents\":\"Châu Á\"}}"
    let dataResult = convertStringToDictionary(text: string)
    print (dataResult)
}



func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.data(using: String.Encoding.utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}

和数据打印:

Optional(["name": Việt NAM, "data": {
capital = "H\U00c0 N\U1ed8I";
continents = "Ch\U00e2u \U00c1";}])

AnyObject 中的数据不是 UTF8。

【问题讨论】:

  • 尝试[String:Any]转换数据
  • 没有问题,就是刚刚打印了字典。如果您访问实际的字典值,那么一切都会按预期进行。

标签: json swift utf-8 nsdictionary nsjsonserialization


【解决方案1】:

出现此问题是因为您尝试直接打印字典的数据而不是访问它的key/value 首先尝试打印所有字典键以获取并查看所有键。

print(parseJSON.allKeys)

它给你例如这些键:[name,data]

然后你可以打印任何你喜欢的键值:

print("Name: \(parseJSON.value(forKey: "name") as! String)")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2014-01-29
    • 1970-01-01
    • 2016-03-23
    • 2013-06-06
    • 2021-10-18
    • 2010-12-04
    相关资源
    最近更新 更多