How to disable TypeNameHandling if specified in attributes using JsonSerializerSettings in Json.NET?

Sometimes I need to suppress the output of "$type"Json.NET properties , even if specified JsonPropertyAttribute.ItemTypeNameHandling. How can I do that?

My root class is as follows:

public class DomainResource
{
    [JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]
    public List<Extension> Extensions { get; set; }
}

And besides, I have a class hierarchy for Extension, for example:

public class Extension
{
    readonly string url;

    public string Url { get { return url; } }

    public Extension(string url)
    {
        this.url = url;
    }
}

public class IntegerExtension : Extension
{
    public IntegerExtension(string url) : base(url) { }

    [JsonProperty("ValueInteger")]
    public int Value { get; set; }
}

I want to ignore ItemTypeNameHandlingin certain scenarios during serialization, but I cannot find a way to do this. I tried setting JsonSerializerSettings using TypeNameHandling.None as input for jsonconvert when I don't need properties "$type"using the following code:

public static string SerializeObject(object value)
{
    JsonSerializerSettings jsonSettings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
        NullValueHandling = NullValueHandling.Ignore,
        TypeNameHandling = TypeNameHandling.None,

    };
    jsonSettings.Converters.Add(new StringEnumConverter
    {
        CamelCaseText = true
    });
    return JsonConvert.SerializeObject(value, Formatting.None, jsonSettings);
}

And then use it like this:

var res = new DomainResource();
res.Extensions = new List<Extension>();
res.Extensions.Add(new IntegerExtension("ewwer"){Value = 3});

var x = CustomJsonConvert.SerializeObject(res);

My desired JSON:

{"extensions": [{"valueInteger": 3, "URL": "ewwer"}]}

"$type", :

{ "": [{ "$ ": "DicomtoJsonConverter.IntegerExtension, DicomtoJsonConverter", "valueInteger": 3, "URL": "ewwer" }]}

"$type" DomainResource class?

+1
1

custom ContractResolver , JsonPropertyAttribute.TypeNameHandling, JsonPropertyAttribute.ItemTypeNameHandling JsonContainerAttribute.ItemTypeNameHandling. :

public class NoTypeNameHandlingContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        // Suppress JsonPropertyAttribute.TypeNameHandling
        property.TypeNameHandling = null;
        // Suppress JsonPropertyAttribute.ItemTypeNameHandling
        property.ItemTypeNameHandling = null;
        return property;
    }

    protected override JsonContract CreateContract(Type objectType)
    {
        var contract = base.CreateContract(objectType);
        if (contract is JsonContainerContract)
        {
            // Suppress JsonContainerAttribute.ItemTypeNameHandling
            ((JsonContainerContract)contract).ItemTypeNameHandling = null;
        }
        return contract;
    }
}

CustomJsonConvert.SerializeObject() :

public static class CustomJsonConvert
{
    // You may want to cache the contract resolver for best performance, see
    // https://stackoverflow.com/questions/33557737/does-json-net-cache-types-serialization-information
    static readonly JsonSerializerSettings jsonSettings;
    static CustomJsonConvert()
    {
        jsonSettings = new JsonSerializerSettings
        {
            ContractResolver = new NoTypeNameHandlingContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy
                {
                    // These are the settings used by CamelCasePropertyNamesContractResolver by default.
                    // Change them if this is not what you want.
                    OverrideSpecifiedNames = true,
                    ProcessDictionaryKeys = true,
                },
            },
            NullValueHandling = NullValueHandling.Ignore,
            TypeNameHandling = TypeNameHandling.None,
            Converters = { new StringEnumConverter { CamelCaseText = true } },
        };
    }

    public static string SerializeObject(object value)
    {
        return JsonConvert.SerializeObject(value, Formatting.None, jsonSettings);
    }
}

Json.NET, 9.0.1, CamelCasePropertyNamesContractResolver DefaultContractResolver, NamingStrategy .

+1

Source: https://habr.com/ru/post/1691907/


All Articles