[英]Serialize/Deserialize nested POCO property without nesting in json.net
考慮:
public class Foo
{
public string FooName { get; set; } = "FooName";
public Bar Bar { get; set; } = new Bar();
}
public class Bar
{
public string BarName { get; set; } = "BarName";
}
如果我們序列化 Foo() output 是:
{"FooName":"FooName","Bar":{"BarName":"BarName"}}
我想:
{"FooName":"FooName", "BarName":"BarName" }
實現這一目標的最干凈的方法是什么?
您可以使用自定義轉換器執行此操作,例如,這是一個快速而骯臟的示例:
public class BarConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => typeof(Bar) == objectType;
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)
{
writer.WriteValue(((Bar)value).BarName);
value.Dump();
}
}
然后像這樣裝飾你的 model:
public class Foo
{
public string FooName { get; set; } = "FooName";
[JsonConverter(typeof(BarConverter))]
public Bar Bar { get; set; } = new Bar();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.