❔ Does System.Text.Json.JsonSerializer allow members to be serialized or do I need properties?
The problem is that my properties commonly have
set
accessors that do things like mark the item dirty. You can't have a property with both set
and init
, or am I misunderstanding something?20 Replies
For me,
set
is also firing off events.
So what should I do?Your serialization DTO really shouldn't be firing events
init
would just set the field. Nothing else.
Which is why I was trying to put the [JsonInclude]
attribute on the field. But I'm getting an exception.no I mean you should ideally be deserializing your json to a separate dto type which you then create your actual entity/model/whatever from
anyway what's the exception?
The non-public property 'strName' on type 'BestChat.IRC.Data.Defs.Network' is annotated with 'JsonIncludeAttribute' which is invalid.'
Well, I'm looking into initializing from a JsonElement
, but I don't see a good way to simply test if a property exists.
I was hoping to do something like x = element.HasProperty(nameof(x)) ? element.GetProperty(nameof(x)) : default;
.
I can't use an enumerator as some fields might be missing from the file and need to be explicitly defaulted before the constructor exits.Thinker
REPL Result: Success
Console Output
Compile: 812.406ms | Execution: 176.700ms | React with ❌ to remove this embed.
is there a reason you can't do something akin to this?
Don't know.
Looks like I have no place with that simple syntax to use
[JsonRequired]
.Does putting a default on that have an effect?
yeah, if you don't provide a value then it'll use that value by default
Thinker
REPL Result: Success
Result: Person
Compile: 647.087ms | Execution: 86.095ms | React with ❌ to remove this embed.
Is the serializer supposed to convert enums for you? The value matches a value from the enum type for a field, but it's throwing an exception.
Though it's reporting the line before the enum value.
Is the enum value in the json a string or number?
string.
In that case you'll have to add a
JsonStringEnumConverter
to the converter in the json settings
Or if you're using .NET 8 then you can use the generic version JsonStringEnumConverter<YourEnum>
I don't see a
JsonStringEnumConverter
.
Is .NET 8 out?System.Text.Json.Serialization.JsonStringEnumConverter
Comes out in November but release candidate 1 is outOK.
Well, now it thinks some required properties are missing.
I don't think they are missing.
I took out the
[JsonRequired]
for the moment so I could get it up. Seems to work that way. I don't understand why it thought it the required fields were missing.
It filled them just fine.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.