码迷,mamicode.com
首页 > Web开发 > 详细

Json.net 动态序列化属性

时间:2019-01-26 13:58:45      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:nbsp   .json   als   jsonp   anr   span   ref   except   console   

环境说明

服务端有个接口,返回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 动态序列化属性

标签:nbsp   .json   als   jsonp   anr   span   ref   except   console   

原文地址:https://www.cnblogs.com/hitearth/p/10323186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!