1. 程式人生 > >Json.net 動態序列化屬性

Json.net 動態序列化屬性

nwr 輸出數據 sys data- exce 客戶 tar != exist

環境說明

服務端有個接口,返回json格式的數據,要求輸出數據的字段由客戶端決定。

測試樣例

using Newtonsoft.Json;
using System;

namespace Hitearth
{
    class Hitearth
    {
        static void Main(string[] args)
        {
            var demos = new[]
            {
                new demo { attr1 = "11", attr2 = "12",attr3 = "13" },
                new demo { attr1 = "21", attr2 = "22",attr3 = "23" },
            };

            var demo2 = new demo();
            demo2.obj = demo2;

            var demo3 = new demo { attr2 = "demo3" };
            demo3.obj = new demo { attr2 = "demo3.obj", obj = new demo { attr2 = "demo3.obj.obj" } };

            Console.WriteLine(JsonConvert.SerializeObject(demos));  // [{"attr1":"11","attr2":"12","attr3":"13","obj":null},{"attr1":"21","attr2":"22","attr3":"23","obj":null}]

            test(demos, "attr1 attr2".Split(‘ ‘)); // [{"attr1":"11","attr2":"12"},{"attr1":"21","attr2":"22"}]
            test(demos, "attr2 attr3".Split(‘ ‘)); // [{"attr2":"12","attr3":"13"},{"attr2":"22","attr3":"23"}]
            test(demos, new string[] { }); // [{},{}]

            test(demo2, "attr2 attr3".Split(‘ ‘));  // {"attr2":null,"attr3":null}
            test(demo2, "attr2 obj".Split(‘ ‘));  // Self referencing loop detected with type ‘Hitearth.demo‘.Path ‘‘.

            test(demo3, "attr2 obj".Split(‘ ‘));// {"attr2":"demo3","obj":{"attr2":"demo3.obj","obj":{"attr2":"demo3.obj.obj","obj":null}}}

        }

        static void test(object obj, string[] attrs)
        {
            try
            {
                Console.WriteLine(JsonConvert.SerializeObject(obj, new FilterPropertiesJsonConverter(typeof(demo), attrs)));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    public class demo
    {
        public string attr1 { get; set; }
        public string attr2 { get; set; }
        public string attr3 { get; set; }
        public demo obj { get; set; }
    }

}

  

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Linq;

namespace Hitearth
{
    /// <summary>
    /// 只序列化 jsonProperties 指定的字段
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FilterPropertiesJsonConverter : JsonConverter
    {
        Type type; 
string[] jsonProperties; bool reversed = false; public FilterPropertiesJsonConverter(Type type, string[] jsonProperties, bool reversed = false) { if (type == null) throw new ArgumentNullException("type"); if (jsonProperties == null) throw new ArgumentNullException("
jsonProperties"); this.type = type; this.jsonProperties = jsonProperties; this.reversed = reversed; } public override bool CanConvert(Type objectType) { return objectType == type; } public override bool CanRead { get { return false; } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); return; } var contract = serializer.ContractResolver.ResolveContract(value.GetType()) as JsonObjectContract; writer.WriteStartObject(); if (contract != null) { foreach (var item in contract.Properties) { if (jsonProperties.Contains(item.PropertyName) == reversed) continue; writer.WritePropertyName(item.PropertyName); serializer.Serialize(writer, item.ValueProvider.GetValue(value)); } } writer.WriteEndObject(); } } }

Json.net 動態序列化屬性