Json 序列化时 [JsonIgnore] 特性使用
- .Net
- 2020-07-23
- 18热度
- 0评论
示例代码:
class Foo
{
public int Id { get; set; }
public string Name { get; set; }
//忽略序列化
[JsonIgnore]
public string AlternateName { get; set; }
//把该属性的名称序列化为另外一个名称
[JsonProperty("Desc")]
[JsonConverter(typeof(StringTruncatingConverter))]
public string Description { get; set; }
[JsonIgnore]
public string Color { get; set; }
}
序列化foo对象:
Foo foo = new Foo
{
Id = 1,
Name = "Thing 1",
AlternateName = "The First Thing",
Description = "123456789",
Color = "Yellow"
};
string json = JsonConvert.SerializeObject(foo, Formatting.Indented);
会输出:
{
"Id": 1,
"Name": "Thing 1",
"Desc": "1234"
}
如何忽略我的自定义获得完整的JSON输出?
class IgnoreJsonAttributesResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
foreach (var prop in props)
{
prop.Ignored = false; // Ignore [JsonIgnore]
prop.Converter = null; // Ignore [JsonConverter]
prop.PropertyName = prop.UnderlyingName; // restore original property name
}
return props;
}
}
序列化foo对象:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new IgnoreJsonAttributesResolver();
settings.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(foo, settings);
输出现在包括被忽略的属性,并且描述不再被截断:
{
"Id": 1,
"Name": "Thing 1",
"AlternateName": "The First Thing",
"Description": "123456789",
"Color": "Yellow"
}

鲁ICP备19063141号
鲁公网安备 37010302000824号