Json.net 动态序列化属性

Posted hitearth

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Json.net 动态序列化属性相关的知识,希望对你有一定的参考价值。

环境说明

服务端有个接口,返回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 动态序列化属性的主要内容,如果未能解决你的问题,请参考以下文章

将 JSON 反序列化为 C# 类,其中 JSON 中的属性名称是动态的

Json.net 忽略实体某些属性的序列化

Json.net反序列化不反序列化所有属性

是否可以将Json.Net设置为忽略$ type?

为啥使用 Json.NET 序列化为 json 字符串时缺少 DriveInfo 的属性?

使用Newtonsoft.Json.dll(JSON.NET)动态解析JSON.net 的json的序列化与反序列化