❔ Deserializing JSON
I'm working on a project where I need to deserialize a JSON api response, and do things with the data. This is a little demo thing:
My issue is, I need to be able to use
Response.Days.FirstDay
, when my JSON response looks like this: {'success': true, 'first_night': 'friday'}
Essentially, I want the DefaultValue
to be present, even if the JSON doesn't contain the 'first_day'
key.
I'm really not sure how to do this, because I'd need to do this with dozens of attributes in about 6 subclasses, so doing it all manually would take ages and doesn't seem good for maintainability.
Any help on how I can achieve this result? To get everything to 'exist' even if it doesn't exist in the JSON, just by using the default value?6 Replies
Well, you can have the optional property be nullable
Then, whenever you access it, simply provide a fallback
object.MaybeNull ?? 0
What about using
[JsonConstructor]
to set the defaults?Or that, yeah
How can I use that?
I decided to use properties with default values instead of a constructor
this outputs
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.