0

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"

0

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.