1

Why doesn't this work?

let jsonResponse = " \"This is a response\" "

let str = try! JSONDecoder().decode(String.self, from: jsonResponse)

print(str)

error: cannot convert value of type 'String' to expected argument type 'Data'

In other languages, like javascript or java/kotlin, converting this response into a string is pretty easy.

JS

const s = JSON.parse(" \"This is a response\" ")

Kotlin

val s = Gson().fromJson(String::class.java, " \"This is a response\" ")

But in swift, it doesn't seem this straight forward. Is this response valid json? I assumed that the double quotes would make it a valid json object.

Thanks in advance.

1
  • You can check if your json is valid here. Commented Jun 18, 2020 at 18:57

1 Answer 1

3

You need to convert the String to Data first to decode it using JSONDecoder:

let jsonResponse = " \"This is a response\" "
let data         = Data(jsonResponse.utf8)
let str          = try! JSONDecoder().decode(String.self, from: data)
print(str)
Sign up to request clarification or add additional context in comments.

2 Comments

This code doesn't seem to work here, any ideas?
This code runs perfectly on Xcode-playgrounds download it from here or if you have Xcode that's more than enough. The thrid-party playground you're using seems to be broken or outdated.

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.