Sometimes I need to suppress output of "$type"
properties by Json.NET even when specified by JsonPropertyAttribute.ItemTypeNameHandling
. How can this be done?
My root class looks like below:
public class DomainResource
{
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]
public List<Extension> Extensions { get; set; }
}
And in addition I have a class hierarchy for Extension
such as the following:
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 ItemTypeNameHandling
in certain scenarios during serialization, but I am not able to find a way to do that.
I tried setting JsonSerializerSettings with TypeNameHandling.None as input for jsonconvert when I do not want "$type"
properties using the code below:
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 as follows:
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 is:
{"extensions":[{"valueInteger":3,"url":"ewwer"}]}
But instead it contains "$type"
properties as shown below:
{"extensions":[{"$type":"DicomtoJsonConverter.IntegerExtension, DicomtoJsonConverter","valueInteger":3,"url":"ewwer"}]}
How can I suppress output of "$type"
properties without changing DomainResource
class?