JSON序列化与包罗万象的词典属性的对象 [英] Serialize json to an object with catch all dictionary property

查看:119
本文介绍了JSON序列化与包罗万象的词典属性的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JSON.net反序列化一个对象,但把未映射特性在字典属性。这可能吗?

I would like to use JSON.net to deserialize to an object but put unmapped properties in a dictionary property. Is it possible?

例如给出的JSON,

 {one:1,two:2,three:3}

和C#类:

public class Mapped {
   public int One {get; set;}
   public int Two {get; set;}
   public Dictionary<string,object> TheRest {get; set;}
}



能否JSON.NET反序列化到一个实例值的一个= 1两= 1,TheRest =字典{{三,3}}

Can JSON.NET deserialize to an instance with values one=1, two=1, TheRest= Dictionary{{"three,3}}

推荐答案

您可以创建一个的 CustomCreationConverter 做你需要做的事情。下面是一个示例(比较难看,但是它展示了你可能会想怎么去这个):

You can create a CustomCreationConverter to do what you need to do. Here's a sample (rather ugly, but demonstrates how you may want to go about this):

namespace JsonConverterTest1
{
    public class Mapped
    {
        private Dictionary<string, object> _theRest = new Dictionary<string, object>();
        public int One { get; set; }
        public int Two { get; set; }
        public Dictionary<string, object> TheRest { get { return _theRest; } }
    }

    public class MappedConverter : CustomCreationConverter<Mapped>
    {
        public override Mapped Create(Type objectType)
        {
            return new Mapped();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var mappedObj = new Mapped();
            var objProps = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();

            //return base.ReadJson(reader, objectType, existingValue, serializer);
            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.PropertyName)
                {
                    string readerValue = reader.Value.ToString().ToLower();
                    if (reader.Read())
                    {
                        if (objProps.Contains(readerValue))
                        {
                            PropertyInfo pi = mappedObj.GetType().GetProperty(readerValue, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                            var convertedValue = Convert.ChangeType(reader.Value, pi.PropertyType);
                            pi.SetValue(mappedObj, convertedValue, null);
                        }
                        else
                        {
                            mappedObj.TheRest.Add(readerValue, reader.Value);
                        }
                    }
                }
            }
            return mappedObj;
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            string json = "{'one':1, 'two':2, 'three':3, 'four':4}";

            Mapped mappedObj = JsonConvert.DeserializeObject<Mapped>(json, new MappedConverter());

            Console.WriteLine(mappedObj.TheRest["three"].ToString());
            Console.WriteLine(mappedObj.TheRest["four"].ToString());
        }
    }
}



所以mappedObj后输出你反序列化JSON字符串将与它的两个属性填充,以及其他一切投入<对象code>词典。当然,我硬编码了一,二值 INT S,但我认为这证明了你会如何去这一点。

So the output of mappedObj after you deserialize the JSON string will be an object with its One and Two properties populated, and everything else put into the Dictionary. Granted, I hard-coded the One and Two values as ints, but I think this demonstrates how you'd go about this.

我希望这有助于

修改:我更新了代码,使其更通用。我没有完全测试它,所以有可能某些情况下,它失败了,但我认为它可以让你最成名的途径。

EDIT: I updated the code to make it more generic. I didn't fully test it out, so there may some cases where it fails, but I think it gets you most of the way there.

这篇关于JSON序列化与包罗万象的词典属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆