Newtonsoft.Json輸出Json時動態忽略屬性

來源:互聯網
上載者:User

標籤:ctr   http   ima   text   price   rri   ignore   繼承   clu   

一,前言

  最近做項目採用Json形式和其他用戶端互動,藉助於Newtonsoft.Json 。

  由於業務情境不同,輸出的Json內容也不同。要想忽略的屬性,可以藉助Newtonsoft.Json的特性,在實體前面添加特性[JsonIgnore]即可,但有時候會根據業務需求,在不同的地方輸出同一個實體中不同的屬性,所以添加特性的方式顯然不能滿足要求。例如user表,在A情境下需要password;B情境下不需要。

二,解決辦法

  可以重寫Newtonsoft.Json的DefaultContractResolver類。

  步驟一:繼承DefaultContractResolver

  建立類繼承Newtonsoft.Json的類 DefaultContractResolver,重寫CreateProperties方法,代碼如下:

    /// <summary>    /// Json分解器    /// </summary>    public class JsonPropertyContractResolver : DefaultContractResolver    {        IEnumerable<string> lstExclude;        public JsonPropertyContractResolver(IEnumerable<string> excludedProperties)        {            lstExclude = excludedProperties;        }                protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)        {            return base.CreateProperties(type, memberSerialization).ToList().FindAll(p => lstExclude.Contains(p.PropertyName));//需要輸出的屬性        }    }
  步驟二:使用方法

  假設我們需要轉化為Json的實體列表是Product,情境一,這個列表中的Price屬性不需要轉成Json到前端;情境二,這個列表中的ShopID和Count屬性不需要轉成Json到前端。代碼如下:

List<Product> ProductList = new List<Product>                                                {                                                    new Product                                                    {                                                        ShopID = 1,                                                        Price=10,                                                        Count=4,                                                        Name = "商品一"                                                    },                                                    new Product                                                    {                                                        ShopID = 2,                                                         Price=11,                                                        Count=3,                                                        Name = "商品二"                                                    },                                                    new Product                                                    {                                                        ShopID = 1,                                                         Price=12,                                                        Count=1,                                                        Name = "商品三"                                                    },                                                    new Product                                                    {                                                        ShopID = 2,                                                         Price=17,                                                        Count=10,                                                        Name = "商品四"                                                    },                                                    new Product                                                    {                                                        ShopID = 3,                                                        Price=13,                                                        Count=2,                                                        Name = "商品五"                                                    }                                                };            //情境一            string jsonString = JsonConvert.SerializeObject(ProductList, Formatting.Indented, new JsonSerializerSettings            {                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,                ContractResolver = new JsonPropertyContractResolver(new List<string> { "ShopID", "Name", "Count" })            });            Console.WriteLine("情境一:" + jsonString);            //情境二            JsonSerializerSettings settings = new JsonSerializerSettings();            settings.Formatting = Formatting.Indented;            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;            settings.ContractResolver = new JsonPropertyContractResolver(new List<string> { "Name", "Price" });            Console.WriteLine("情境二:" + JsonConvert.SerializeObject(ProductList, settings));

  輸出結果:

 

Newtonsoft.Json輸出Json時動態忽略屬性

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.