【发布时间】:2017-02-22 03:17:16
【问题描述】:
我有包含标识符的类,像这样;
public class Type1
{
public int Id { get; set; }
// other properties
}
public class Type2
{
public int Id { get; set; }
// other properties
}
public class ParentType
{
[JsonConverter(typeof(IdConverter))]
public Type1 Instance1 { get; set; }
[JsonConverter(typeof(IdConverter))]
public Type2 Instance2 { get; set; }
}
我想将ParentType 序列化为 Json,但我不需要序列化整个班级。我只需要 Id,因为它唯一地标识了实例。 IdConverter 是这样实现的;
class IdConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
PropertyInfo pi = objectType.GetProperty("Id");
return (pi != null && pi.PropertyType == typeof(int));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
int id = (int)value.GetType().GetProperty("Id").GetValue(value);
JObject o = JObject.FromObject(new { Id = id });
o.WriteTo(writer);
}
}
}
这工作正常,但输出的 Json 格式不理想;
{
"Instance1": {
"Id": 1
},
"Instance2": {
"Id": 2
}
}
我希望它看起来更像这样;
{
"Instance1": 1,
"Instance2": 2
}
有什么方法可以实现吗?
【问题讨论】: