How Deserialize `{}` to null
#114063
-
there is a json string {
"mainInfo": {}
} class code public class TypeA
{
public MainInfo? MainInfo {get;set;}
}
public class MainInfo
{
public string? Name {get;set;}
public string? Address {get;set;}
} and deserialize it {
"mainInfo": {
"name": null,
"address": null
}
} the result in my wish is {
"mainInfo": null
} |
Beta Was this translation helpful? Give feedback.
Answered by
am11
Mar 31, 2025
Replies: 1 comment 2 replies
-
I try to write JsonTypeInfoResolver public class MyTypeResolverTypeResolver : DefaultJsonTypeInfoResolver
{
public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
{
JsonTypeInfo typeInfo = base.GetTypeInfo(type, options);
if (type == typeof(TypeA))
{
foreach (var property in typeInfo.Properties.Where(p => p.PropertyType == typeof(MainInfo)))
{
property
.ShouldSerialize = (obj, value) => value is MainInfo v && (v.Name != null || v.Address != null);
}
}
return base.GetTypeInfo(type, options);
}
} but it not work |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something like https://dotnetfiddle.net/WyUEiW.