使用自定义JsonConverter,您可以控制转换以输出您想要的任何内容。
类似:
public class BarConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Bar);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var bar = value as Bar;
serializer.Serialize(writer, bar.Name);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Note: if you need to read to, you'll need to implement that here too
// otherwise just throw a NotImplementException and override `CanRead` to return false
throw new NotImplementedException();
}
}
然后,您可以使用JsonConverterAttribute 装饰您的属性或Bar 类(取决于您是否总是希望Bar 像这样序列化,或者仅用于此属性):
[JsonConverter(typeof(BarConverter))]
public Bar Bar { get; set; }
或者:
[JsonConverter(typeof(BarConverter))]
public class Bar
另一种“快速而肮脏”的方法是只拥有一个将被序列化的 shadow 属性:
public class Foo
{
[JsonProperty("bar")] // this will be serialized as "bar"
public string BarName
{
get { return Bar.Name; }
}
[JsonIgnore] // this won't be serialized
public Bar Bar { get; set; }
}
请注意,如果您希望能够阅读,那么您还需要提供一个 setter 并弄清楚如何将字符串名称转换回 Bar 的实例。这就是快速而肮脏的解决方案有点令人不快的地方,因为您没有简单的方法将设置 BarName 限制为仅在反序列化期间。