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
 











免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM