3

i want to save a JSON-String into an existing Object in Swift:

This is my Object:

struct Benutzer : Decodable, Encodable{
let userRights: [String]
}

This is my String:

str = "{"user_rights":["terminal_create"]}"

That is my Code:

do { let data1 = str.data(using: String.Encoding.utf8, allowLossyConversion: false)

let User = try JSONDecoder().decode(Benutzer.self, from: data1 as Data)

print(User)

 }catch{
       print("Error serializing!")
  }

With this code, "Error serializing!" shows up every time. Do you guys know whats up? Sorry, I am still a complete beginner. Sorry for not formatting the question I don't quite get it :( I get this String from another JSON request: I get this as an answer, the JSON data string that I want to decode is part of that answer:

Answer(api_version: 1, result: "login", success: true, token: "da39a3ee5e6b4b0d3255bfef95601890afd80709", data: "{\"user_rights\":[\"terminal_create\"]}")

This is a Answer-Object:

struct Answer: Decodable, Encodable{

    let api_version: Int
    let result: String
    let success: Bool
    let token: String
    let data: String

}

Maybe you know another way how to extract that Data into a Benutzer Object. I would be really thankful, thanks a lot guys!

3
  • Show us the exact value of str. And print the error in your catch: print("Error serializing: \(error)"). Commented Jun 7, 2018 at 20:50
  • str = String = "{"user_rights":["terminal_create"]}" Commented Jun 7, 2018 at 20:55
  • Error serializing: keyNotFound(CodingKeys(stringValue: "userRights", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"userRights\", intValue: nil) (\"userRights\").", underlyingError: nil)) Commented Jun 7, 2018 at 20:55

1 Answer 1

1

your coding key not similar to what in your string userRights , user_rights

so do like that:

struct Benutzer: Codable {
        let userRights: [String]

        enum CodingKeys: String, CodingKey {
            case userRights = "user_rights"
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much I completely overlooked that! Now it works. Thanks!

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.