0

I am trying to encode my jsonData. All works fine with one exception - I am receiving as output Optional(my_json_string). But I want to receive only my_json_string

When I change req.httpBody = jsonData to req.httpBody! = jsonData, I am getting an error.

do {
    let jsonData = try encoder.encode(self)
    let jsonString = String(data: jsonData, encoding: .utf8)
    req.httpBody = jsonData
    print ("httpBody is: ", jsonString)
} catch {
    //TODO:error handling
}

How to do it correctly and unwrap my JSON string from optional?

0

1 Answer 1

6

There's no issue with your code, your encoded JSON isn't Optional. The issue you see is that you are printing the return value of the String(data:, encoding: ) initializer, which is a failable initializer (it returns nil if the encoding you supplied to it is wrong), hence the Optional in the print statement.

JSONEncoder always produces a valid UTF-8 encoded String, so you can safely force unwrap the return value of the initializer by doing

let jsonString = String(data: jsonData, encoding: .utf8)!
Sign up to request clarification or add additional context in comments.

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.