您可以通过创建自定义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}
这是你想要的?