简体   繁体   中英

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

JObject has a Merge method:

var json1 = JObject.FromObject(obj1);
var json2 = JObject.FromObject(obj2);
json1.Merge(json2);

// json1 now contains the desired result

fiddle


If your objects contain properties with the same name, you can use the overload taking a JsonMergeSettings object to specify how conflicts should be resolved.

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