提问者:小点点

在JSON.NET中序列化/反序列化不嵌套的嵌套POCO属性


考虑:

 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" }

最干净的方法是什么?


共1个答案

匿名用户

您可以使用自定义转换器来完成此操作,例如,这是一个快速而肮脏的示例:

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