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 ItemTypeNameHandling
in 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?