-
Hi, I know that caching and reusing JsonSerializerOptions is the best practice, however I need to be able to specify which properties to serialize. The thing is, I send patch requests to OData service and most of the time I only need to change a value of a few fields and not all of them, so I need to serialize only the properties that I want to change. I decided to use TypeInfoResolver, but as the properties vary, I have to create new instance of JsonSerializerOptions for every serialization, I am aware that this is not a good practice and I have already thought of some alternative ways of achieving what I want, but I am not yet very experienced in the field, so could you recommend anything? Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I believe you should be able to achieve this by using a modifier method for
Be aware that the A rather simple and silly example illustrating a modifier method altering private static void ContractModifier_SerializeFooOrNot(JsonTypeInfo contract)
{
if (contract.Kind != JsonTypeInfoKind.Object)
return;
// if (contract.Type == someTypeOfInterest)
// { ...
foreach (var prop in contract.Properties)
{
var originalShouldSerialize = prop.ShouldSerialize;
prop.ShouldSerialize =
(originalShouldSerialize is null) ? (object owningObject, object? propertyValue) => ShouldSerializeProperty(prop, owningObject, propertyValue)
: (object owningObject, object? propertyValue) => originalShouldSerialize(owningObject, propertyValue) && ShouldSerializeProperty(prop, owningObject, propertyValue);
}
static bool ShouldSerializeProperty(JsonPropertyInfo property, object owningObject, object? propertyValue)
{
return (property.Name == "Foo") ? _serializeFoo : true;
}
}
private static bool _serializeFoo = true; The example disabling the serialization of the Foo property in action: https://dotnetfiddle.net/jQv7tJ. Note that the demo uses only a single JsonSerializerOptions instance and a single JsonTypeInfoResolver instance. |
Beta Was this translation helpful? Give feedback.
I believe you should be able to achieve this by using a modifier method for
JsonTypeInfo
's generated by the JsonTypeInfoResolver. A resolver with such a modifier method can be derived from the used JsonTypeInfoResolver (whether it's the default reflection-based resolver or one generated by the STJ source generator) using the WithAddedModifier extension method.JsonTypeInfo
instances representing types that will be serialized as json objects (i assume the types you are interested in are) possess a list ofJsonPropertyInfo
instances representing serializable properties.JsonPropertyInfo
has an optionalShouldSerialize
predicate delegate, which allows you to assign a method/function to contr…