2

我有以下类定义:

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 转换?

4

2 回答 2

2

您可以通过创建自定义JsonConverter类来做到这一点。也许是这样的:

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;
    }
}

然后你会像这样使用它:

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 如下所示:

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

这是你想要的?

于 2013-07-29T16:53:30.903 回答
0

我做了额外的属性只是将数据戳回基本字典。通过这种方式,您可以公开像“Id”这样的属性,但在序列化/反序列化期间,它只会与底层字典一起使用:

public class ElasticObject : Dictionary<string, object>
{
    public int Id
    {
        get { 
            int val;
            if (int.TryParse(this["Id"] as string, out val))
            {
                return val;
            }

            return -1;
        }
        set { this["Id"] = value; }
    }
}
于 2015-04-21T23:20:11.783 回答