❔ How to Require Property for Serialization?

Hello, I'm working on a library for the Unity game engine that interfaces with an API. Some of the endpoints require the presence of a property for it to be a valid request. I'm using Newtonsoft.Json for my serialization/deserialization. I saw that it had a [JsonProperty(Required = Required.Always)] attribute, but apparently this only restricts deserialization. Is there any way to restrict serialization as well? Looking to throw an exception or something if developer tries to serialize an object without a required property. I'm not attached to Newtonsoft if there is another library that has this functionality. Thanks!
7 Replies
Angius
Angius2y ago
Use a constructor for that class? I'd say use required properties, but alas, Unity is quite a few years behind And first and foremost, don't let the user just send their own stuff to that API Wrap it up fully So that the user only calls, say
var client = new SomeApiClient();
client.Send(new SomeApiData("bob", 42, false));
var client = new SomeApiClient();
client.Send(new SomeApiData("bob", 42, false));
Don't expose serialization and deserialization Provide the client, and provide whatever classes the client will work with
davejrodriguez
davejrodriguezOP2y ago
Right yeah, that's the plan Good advice They say they're planning on catching up 🤞 but until then
Angius
Angius2y ago
Required properties are a .NET 7 thing If Unity actually updates to .NET 6 sometime this decade it'll be a resounding success
davejrodriguez
davejrodriguezOP2y ago
They've said they plan on getting to .NET 7.x or 8 sometime in 2024. We'll see.
Angius
Angius2y ago
Oh they've said a lot lol How's DOTS doing mweh
davejrodriguez
davejrodriguezOP2y ago
1.0 almost out lol
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server