如何使JsonConverter写入键/值而不是键/数组

时间:2017-02-21 19:13:56

标签: json json.net

我的类包含标识符,如下所示;

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
}

我能通过某种方式实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

抱歉,我自己解决了这个问题;

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);
        writer.WriteValue(id);
    }
}

结果;

{
  "Instance1": 1,
  "Instance2": 2
}