简体   繁体   English

如何快速解析JSON(将JSON字符串转换为字符串)

[英]How to parse json in swift (convert json string to string)

I don't find a way to parse a simple json object into a string object in swift. 我找不到一种快速地将简单的json对象解析为字符串对象的方法。 I have a network request which gives me this json response: 我有一个网络请求,它给了我这个json响应:

"\"asdf\""

When I try to parse this into a string in swift it looks like this: 当我尝试快速将其解析为字符串时,它看起来像这样:

"\"asdf\""

according this documentation from apple I should only need to do this: 根据苹果公司的这份文件,我只需要这样做:

Apple Swift documentation Apple Swift文档

let jsonValue = responseData as? String

But that does not work for me. 但这对我不起作用。

I need just asdf as string value. 我只需要asdf作为字符串值。

Can anyone help me out? 谁能帮我吗?

Thanks in advance. 提前致谢。

EDIT: 编辑:

Here is my network request code: 这是我的网络请求代码:

let stringUrl = "https://test.fangkarte.de/v1.3/test"
    let url = URL(string: stringUrl)!
    let request = URLRequest(url: url)
    let session = URLSession(configuration: URLSessionConfiguration.default)
    let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
        if let data = data {
            let json = String(data: data, encoding: String.Encoding.utf8)
            let response = response as! HTTPURLResponse
            if 200...299 ~= response.statusCode {
                callback(true, response.statusCode, json!)
            } else {
                callback(false, response.statusCode, json!)
            }
        }
    })
    task.resume()

The value of the variable json is "\\"testString\\"" and not "testString" 变量json的值为"\\"testString\\""而不是"testString"

You could try something like: 您可以尝试类似:

func parseJSON(_ data: Data) -> [String: Any]? {

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
            let body = json["data"] as? [String: Any] {
            return body
        }
    } catch {
        print("Error deserializing JSON: \n\(error)")
        return nil
    }
    return nil
}

To use: 使用方法:

let data = <variable holding JSON>.data(using: .utf8)
let jsonResult = parseJSON(data)

You get a json string so you can try 您会得到一个json字符串,因此您可以尝试

  let jsonstring = "\"asdf\""
  let data = jsonstring.data(using: .utf8)

do {
     if let str = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? String {
        print(str)
     }

   }
   catch let caught as NSError
   {
   }

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

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