我有以下课程定义:
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转换?
答案 0 :(得分: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}
这是你在找什么?
答案 1 :(得分: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; }
}
}