有时我需要抑制输出"$type"
即使由 Json.NET 指定属性JsonPropertyAttribute.ItemTypeNameHandling https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonPropertyAttribute_ItemTypeNameHandling.htm。如何才能做到这一点?
我的根类如下所示:
public class DomainResource
{
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]
public List<Extension> Extensions { get; set; }
}
另外我还有一个类层次结构Extension
例如以下内容:
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; }
}
我想忽略ItemTypeNameHandling
在序列化过程中的某些情况下,但我无法找到一种方法来做到这一点。
当我不想要时,我尝试使用 TypeNameHandling.None 设置 JsonSerializerSettings 作为 jsonconvert 的输入"$type"
使用以下代码的属性:
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);
}
然后使用它如下:
var res = new DomainResource();
res.Extensions = new List<Extension>();
res.Extensions.Add(new IntegerExtension("ewwer"){Value = 3});
var x = CustomJsonConvert.SerializeObject(res);
我想要的 JSON 是:
{"extensions":[{"valueInteger":3,"url":"ewwer"}]}
但它包含"$type"
属性如下图:
{“扩展”:[{“$ type”:“DicomtoJsonConverter.IntegerExtension,
DicomtoJsonConverter","valueInteger":3,"url":"ewwer"}]}
我怎样才能抑制输出"$type"
特性不改变DomainResource
class?