My Realm model is also codable, and theses properties can be null, but when I get the JSON from the serve and decode it. It’s not working because he doesn’t know map the optional value
I need to implement the decoder method to solve this. I don’t want to implement decoder to all my realm model
There is an optional persisted propertyWrapper @OptionalPersisted something like this?
Which properties? Can you include the Realm Model you’re referring to and perhaps a brief segment of the JSON you’re working with? Also, a snippet of the code you’ve attempted would be very helpful in clarifying the question
The error that I get Decoded JSON error: valueNotFound(Swift.Optional<Swift.String>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "phoneNB", intValue: nil)], debugDescription: "Expected Optional<String> but found null value instead.", underlyingError: nil))
It’s fail on phoneNB field. In my Realm model I marked it optional ?
Forgive the question but at first glance, the Realm object model Supplier doesn’t appear to match the presented JSON - the JSON data is a tier lower within a data child node. Perhaps there’s a third party library installed or more to it?
But the question is about the optional value so I simplified your json data just for testing with optionals to this:
let supplierJSONString =
{
"phoneNB":null,
"id":"477076BB-3114-4750-8E4F-042EF65B31E0",
"name":"sup"
}
and then created a Realm Model to map it to
class Supplier: Object, Codable {
@Persisted(primaryKey: true) var id: UUID = UUID()
@Persisted var name: String = ""
@Persisted var phoneNB: String?
}
and then some quick code to encode the JSON string and then decode it into the Realm object
let jsonData = self.supplierJSONString.data(using: .utf8)!
let response = try! JSONDecoder().decode(Supplier.self, from: jsonData)
print(response)
and printed to console
Supplier {
id = 477076BB-3114-4750-8E4F-042EF65B31E0;
name = sup;
phoneNB = (null);
}
So it looks like the optional is being set to NULL as it should.
Perhaps a bit more clarity in the question and model would help us narrow the issue?