我有一个这样的对象:
[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 }
可悲的是,我无法从数据类派生。
答案 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);
}