1

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"
}
5
  • Does this answer your question? Merge two objects during serialization using json.net? Commented Oct 22, 2021 at 11:40
  • Do you want to merge them as strings? Commented Oct 22, 2021 at 11:46
  • @gunr2171 the only generic solution in there involves authoring your own converter, which I just cannot believe is the nicest method Commented Oct 22, 2021 at 11:47
  • @Heinzi good thought, but I'd rather convert each to an intermediary object before serialising that - seems far more efficient... currently looking into Json.NET's Linq.JObject for that Commented Oct 22, 2021 at 11:48
  • @AndriyShevchenko I mean, necessarily I think I'd need to merge them as abstract objects...? Commented Oct 22, 2021 at 11:49

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I also like that I can just json1.ToObject<object>() if I want to keep it as an object for later use/serialization (which I actually do in my case, since this combined object ends up becoming part of an ASP.NET controller response!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.