简体   繁体   中英

Serialize/Deserialize nested POCO property without nesting in json.net

Consider:

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

If we serialize Foo() the output is:

{"FooName":"FooName","Bar":{"BarName":"BarName"}}

I want:

{"FooName":"FooName", "BarName":"BarName" }

What is the cleanest way of achieving this?

You can do this with a custom converter, for example, this is a quick and dirty example:

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

And then decorate your model like this:

public class Foo
{
    public string FooName { get; set; } = "FooName";

    [JsonConverter(typeof(BarConverter))]
    public Bar Bar { get; set; } = new Bar();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM