HonQii
HonQii

Reputation: 43

Swift 4 JSONEncoder can not encode String or Int, But they followed Codable protocol

let encoder = JSONEncoder()

do {
   let encodData = try encoder.encode("test string") // same as Int type
   print(encodData) // nil
} catch let err {
   print(err.localizedDescription) // The data couldn’t be written because it isn’t in the correct format.
}

how to encode these type value

Upvotes: 4

Views: 3270

Answers (1)

Martin R
Martin R

Reputation: 539715

The top-level (root) JSON object can only be an array or dictionary. For example:

do {
    let encoder = JSONEncoder()
    let encodData = try encoder.encode(["test string"])
    print(String(data: encodData, encoding: .utf8)!) 
    // ["test string"]

} catch {
    print(error.localizedDescription)
}

Upvotes: 5

Related Questions