Jan
Jan

Reputation: 13

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. I have a network request which gives me this json response:

"\"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

let jsonValue = responseData as? String

But that does not work for me.

I need just asdf as string value.

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"

Upvotes: 0

Views: 4783

Answers (2)

JaredH
JaredH

Reputation: 2398

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)

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100523

You get a json string so you can try

  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
   {
   }

Upvotes: 0

Related Questions