【问题标题】:How to format a JSON String in Swift?如何在 Swift 中格式化 JSON 字符串?
【发布时间】:2023-03-29 09:04:01
【问题描述】:

我有一个 JSON 字符串,其格式类似于 { name: "John" } 而不是 { "name" : "John"},每当我尝试访问名称键时都会导致结果为零,因为:

Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 1."

我正在寻找一个可以将这个 JSON 文件修复/解析/格式化为可读的函数? JSON Format 这样的网站是怎么做到的?

【问题讨论】:

  • 你可以先责怪字符串创建者 ;-)
  • JSON 字符串是否只是在 String 类型的变量中?
  • @OlivierWilkinson 是的,它是一个字符串类型的变量。
  • @WilliamHu 我之前查过。我无法从 JSON Lint 等网站复制粘贴经过验证的字符串,我需要通过一种方法将该字符串转换为可读/有效的内容。

标签: json swift


【解决方案1】:

有趣的是,{ name: "John" } 在 Javascript 中创建了一个有效的 JSON 对象。所以你的问题现在变成了为 Swift 寻找一个 Javascript 解释器!

Mac OS X 和 iOS 的最新版本内置了一个:WKWebView。它是一个带有 Javascript 解析器的网络渲染引擎。将您的目标与 WebKit 链接并尝试以下操作:

import WebKit

class MyJSONParser {
    private static let webView = WKWebView()

    class func parse(jsonString: String, completionHandler: (AnyObject?, NSError?) -> Void) {
        self.webView.evaluateJavaScript(jsonString, completionHandler: completionHandler)
    }
}

用法:

let str = "{ firstName: 'John', lastName: 'Smith' }"

// You must assign the JSON string to a variable or the Javascript
// will return void. Note that this runs asynchronously
MyJSONParser.parse("tmp = \(str)") { result, error in
    guard error == nil else {
        print(error)
        return
    }
    if let dict = result as? [String: String] {
        print(dict)
    } else {
       print("Can't convert to Dictionary")
    }
}

斯威夫特 3

import WebKit
class MyJSONParser {
    private static let webView = WKWebView()

    class func parse(jsonString: String, completionHandler: @escaping (Any?, Error?) -> Void) {
        self.webView.evaluateJavaScript(jsonString, completionHandler: completionHandler)
    }
}

let str = "{ firstName: 'John', lastName: 'Smith' }"

// You must assign the JSON string to a variable or the Javascript
// will return void. Note that this runs asynchronously
MyJSONParser.parse(jsonString: "tmp = \(str)") { result, error in
    guard error == nil else {
        print(error!)
        return
    }
    if let dict = result as? [String: String] {
        print(dict)
    } else {
        print("Can't convert to Dictionary")
    }
}

【讨论】:

  • 当我在 Playground 中尝试时,什么都没有打印出来。这是screenshot
猜你喜欢
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多