I know that this solution is a hack. But so far, I haven't come up with anything better for my needs.
There is a class:
public class Request
{
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
}
I need to ignore the "Age" property during deserialization, but I need it during serialization.
So far, I have only come up with using two serializers: System.Text.Json and Newtonsoft, and leaving the [JsonIgnore] attribute for the System.Text.Json serializer only. When I need to include the "Age" field, I will use Newtonsoft.
But I feel that this is very hacky, and I don't like this plan.
Why I'm resorting to a hack:
Why am I even resorting to a hack: At one point, I make a request to an external system. The external system returns the same results for identical requests (if it matters, it's a service for building routes from point A to point B, disregarding traffic). I don't want to burden the external system with unnecessary requests.
So, I've decided to cache the requests. The problem is that the "request" is an object (in this example, it's a type of Request) that comes to me in the controller. In other words, it's a new object every time, even if the contents of the request are the same.
Therefore, I decided to use a serialized string as the cache key.
There are three alternatives that came to mind.
1. Records. I'm not sure if the cache will use full comparison instead of reference comparison. But it's worth testing and not dismissing this option.
2. Caching md5. Honestly, I'm scared of collisions here. If they occur (and everything bad should happen sooner or later), then I'll be debugging the code for a long time and not understanding why I'm getting the wrong route. A partial solution would be to use more complex hashing algorithms, but then the question of performance becomes even more acute.
3. (As I was writing this question, I realized that I like this option even more than using two serializers). Cache the combination of the URL and body of the request that I want to send to the external service.