如何序列化属性,就好像它是基类一样?

时间:2019-04-05 15:45:17

标签: c# json properties json.net deserialization

我有一个这样的对象:

[JsonObject]
public class Thing<T> where T: class
{
    [JsonProperty()]
    T Data { get; set; }

    [JsonProperty("error")]
    public int ErrorCode { get; set; }
}

T是具有单个 value 属性的类时,是否有一种使其序列化的方法,例如:

{ value: "content", error: 1 }

代替此:

{ data: { value: "content" }, error: 1 }

可悲的是,我无法从数据类派生。

1 个答案:

答案 0 :(得分:0)

例如,您将需要一个自定义转换器:

[JsonConverter(typeof(HasValueConverter))]
public class HasValue
{
    public HasValue(string value)
    {
        this.Value = value;
    }

    public string Value { get; set; }
}

[JsonObject]
public class Thing<T> where T: class
{
    [JsonProperty("value")]
    public T Data { get; set; }

    [JsonProperty("error")]
    public int ErrorCode { get; set; }
}

class HasValueConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(HasValue);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new HasValue(JToken.Load(reader).Value<string>());
    }

    public override bool CanWrite => false;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

[Test]
public void Deserializes()
{
    var json = "{ value: \"content\", error: 1 }";
    var thing = JsonConvert.DeserializeObject<Thing<HasValue>>(json);
    Assert.AreEqual("content", thing.Data.Value);
}