vendredi 22 octobre 2021

With Json.NET, how can I merge two C# objects that need to be serialized together?

Say I have some classes that I often serialize normally, such as

public class A
{
    public A(int x, bool y)
    {
        X = x;
        Y = y;
    }

    [JsonProperty("x_thing")]
    public int X { get; }

    [JsonProperty("y_thing")]
    public bool Y { get; }
}

public class B
{
    public B(string s)
    {
        S = s;
    }

    [JsonProperty("string_thing")]
    public string S { get; }
}

If I want to start here (but pretend A and B are arbitrary objects):

var obj1 = new A(4, true);
var obj2 = new B("hello world");

... then how can I idiomatically produce this JSON serialization?

{
    "x_thing": 4,
    "y_thing": true,
    "string_thing": "hello world"
}




Aucun commentaire:

Enregistrer un commentaire