序列化/反序列化嵌套的POCO属性,而不在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((,输出为:

{"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();
}
}

然后像这样装饰你的模型:

public class Foo
{
public string FooName { get; set; } = "FooName";
[JsonConverter(typeof(BarConverter))]
public Bar Bar { get; set; } = new Bar();
}

最新更新