Raphael Schmidt
Raphael Schmidt

Reputation: 33

Save JSON String in Object

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!

Upvotes: 3

Views: 124

Answers (1)

Abdelahad Darwish
Abdelahad Darwish

Reputation: 6067

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

Upvotes: 1

Related Questions