繁体   English   中英

如何将字符串转换为 json 字典。?

[英]How to convert string to json dictionary.?

下面的一段代码,我用来将string转换为dictionary ,但不工作。

let body = "{status:0}"
do {
    let dictionary = try convertToDictionary(from: body ?? "")
    print(dictionary) // prints: ["City": "Paris"]
} catch {
    print(error)
}

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }

    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])

    return anyResult as? [String: String] ?? [:]
}

两个问题:

  1. 该值为Int ,因此类型转换为[String:String]失败。
  2. JSON 格式需要用双引号括起来的键。

这适用于any值类型

let body = """
{"status":0}
"""

do {
    let dictionary = try convertToDictionary(from: body)
    print(dictionary) // prints: ["City": "Paris"]
} catch {
    print(error)
}

func convertToDictionary(from text: String) throws -> [String: Any] {
    let data = Data(text.utf8)
    return try JSONSerialization.jsonObject(with: data) as? [String:Any] ?? [:]
}

我会推荐你使用Codable协议。 而不是使用字典,而是使用一些特定的类/结构来解析数据。 您可以使用与此类似的代码:

struct Status: Codable {
    let status: Int
}

let body = "{\"status\":0}".data(using: .utf8)!
do {
    let decoder = JSONDecoder()
    let status = try decoder.decode(Status.self, from: body)
    print(status) //Status(status: 0)
} catch {
    print("\(error)")
}

这是处理 JSON 响应的更安全的方法。 此外,它还为您提供了有关问题所在的信息,因此您可以轻松修复它。 例如,如果你使用let status: String你会得到这个错误:

typeMismatch(Swift.String, 
Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "status", intValue: nil)], 
debugDescription: "Expected to decode String but found a number instead.", 
underlyingError: nil))

有关Codable的更多信息,您可以在 Apple 编写的Encoding and Decoding Custom Types文章中阅读,或在线搜索Codable教程 - 有很多关于它的好文章。

let body = "{\"status\":\"0\"}" 

do {
     let dictionary = try convertToDictionary(from: body )
      print(dictionary) 
   } catch {
        print(error)
  }

func convertToDictionary(from text: String) throws -> [String: Any] {
    if let data = text.data(using: .utf8) {
        do {
            return try (JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] ?? [:])
        } catch {
            print(error.localizedDescription)
        }
    }

    return [:]
}

输出 -> [“状态”:0]

由于输入字符串不是 json 我建议使用非 json 解决方案

let array = body.dropFirst().dropLast().split(separator: ":").map {String($0)} 

var dictionary = [String: String]()
if let key = array.first, let value = array.last { 
    dictionary[key] = value
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM