'Encoding Realm models using @Persisted gives a Swift EncodingError message

When trying to encode this:

class MyClass: Object, Codable {
  @Persisted var someValue: String
}

// I've created and added MyClass to Realm. I then query for it and get a `myClassResult` object 

let jsonString = try myClassResult.encode(to: JSONEncoder())

I get this error:

Swift.EncodingError.invalidValue(RealmSwift.Persisted<Swift.String>(storage: RealmSwift.(unknown context at $10d2a3778).PropertyStorage<Swift.String>.managed(key: 0)), Swift.EncodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "someValue", intValue: nil)], debugDescription: "Only unmanaged Realm objects can be encoded using automatic Codable synthesis. You must explicitly define encode(to:) on your model class to support managed Realm objects.", underlyingError: nil))

Encoding and decoding worked on earlier versions of Realm when using the @objc dynamic var annotation. The error began when I updated my code to use Realm v.10.21.0 with the @Persisted annotation.



Solution 1:[1]

You need to implement encode(to:) on your model class:

class MyClass: Object, Codable {
    @Persisted var someValue: String

    enum CodingKeys: String, CodingKey {
        case someValue
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(someValue, forKey: .someValue)
    }
}

// After querying for a `myClassResult` object.

do {
    let jsonString = try myClassResult.encode(to: JSONEncoder())

} catch {
    print(error)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1