Json convert object which inherit dictionary

后端 未结 2 1698
日久生厌
日久生厌 2021-01-07 04:36

I have following class definition:

public class ElasticObject : Dictionary
{
    public int Id { get;set;}
}

var keyValues = new Elast         


        
2条回答
  •  旧时难觅i
    2021-01-07 05:05

    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(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>(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 { new ElasticObjectConverter() }
    };
    
    var keyValues = new ElasticObject();
    keyValues.Id = 200000;
    keyValues.Add("Price", 12.5);
    
    var json = JsonConvert.SerializeObject(keyValues, settings);
    

    The JSON produced by the above would look like this:

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

    Is this what you are looking for?

提交回复
热议问题