Json转换继承字典的对象 [英] Json convert object which inherit dictionary

查看:78
本文介绍了Json转换继承字典的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程定义:

public class ElasticObject : Dictionary<string, object>
{
    public int Id { get;set;}
}

var keyValues = new ElasticObject();
keyValues.Id= 200000;
keyValues.Add("Price", 12.5);
var json = JsonConvert.SerializeObject(keyValues,
           new JsonSerializerSettings{NullValueHandling = NullValueHandling.Ignore});

已解析的json字符串为{"Price":12.5},该字符串无法包含Id属性,是否可以自定义json转换?

The parsed json string is {"Price":12.5} which fails to contain the Id property, is there any way to customize the json conversion?

推荐答案

您可以通过创建自定义的JsonConverter类来实现.也许是这样的:

You can do this by making a custom JsonConverter class. Perhaps something like this:

class ElasticObjectConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(ElasticObject));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        ElasticObject eobj = (ElasticObject)value;
        var temp = new Dictionary<string, object>(eobj);
        temp.Add("Id", eobj.Id);
        serializer.Serialize(writer, temp);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var temp = serializer.Deserialize<Dictionary<string, object>>(reader);
        ElasticObject eobj = new ElasticObject();
        foreach (string key in temp.Keys)
        {
            if (key == "Id")
                eobj.Id = Convert.ToInt32(temp[key]);
            else
                eobj.Add(key, temp[key]);
        }
        return eobj;
    }
}

然后您将像这样使用它:

You would then use it like this:

var settings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    Converters = new List<JsonConverter> { new ElasticObjectConverter() }
};

var keyValues = new ElasticObject();
keyValues.Id = 200000;
keyValues.Add("Price", 12.5);

var json = JsonConvert.SerializeObject(keyValues, settings);

上面生成的JSON看起来像这样:

The JSON produced by the above would look like this:

{"Price":12.5,"Id":200000}

这是您要寻找的吗?

这篇关于Json转换继承字典的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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