C#中[JsonIgnore]意义

字面意义是忽略序列化,就是当字段在序列化时,被[JsonIgnore]标记了的字段将被忽略序列化

 

序列化输出中使用Id和Name属性,但我绝对不会对AlternateName和Color感兴趣.我用[JsonIgnore]标记了那些.我希望描述出现,但有时这可能会变得很长,所以我使用自定义JsonConverter来限制它的长度.我还想使用较短的属性名称来描述,所以我用[JsonProperty(“Desc”)]标记了它.

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 = new Foo
{
    Id = 1,
    Name = "Thing 1",
    AlternateName = "The First Thing",
    Description = "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
    Color = "Yellow"
};

string json = JsonConvert.SerializeObject(foo, Formatting.Indented);

…我得到这个输出:

{
  "Id": 1,
  "Name": "Thing 1",
  "Desc": "This is some lengthy text describing Thing 1 "
}

我有时想获得完整的JSON输出,忽略我的自定义.我可以使用自定义ContractResolver以编程方式“取消应用”类中的属性.这是解析器的代码:

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;
    }
}

要使用解析器,我将它添加到JsonSerializerSettings并将设置传递给序列化器,如下所示:

 

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": "This is some lengthy text describing Thing 1 which you'll no doubt find very interesting and useful.",
  "Color": "Yellow"
}


原文:http://www.voidcn.com/article/p-uvkjwmre-bub.html
 










posted on 2019-09-04 15:48  HelloOcean  阅读(9252)  评论(0)    收藏  举报

导航