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"
}
Archimaredes
  • 1,397
  • 12
  • 26
  • Does this answer your question? [Merge two objects during serialization using json.net?](https://stackoverflow.com/questions/19811301/merge-two-objects-during-serialization-using-json-net) – gunr2171 Oct 22 '21 at 11:40
  • Do you want to merge them as strings? – Andriy Shevchenko Oct 22 '21 at 11:46
  • @gunr2171 the only generic solution in there involves authoring your own converter, which I just cannot believe is the nicest method – Archimaredes Oct 22 '21 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 – Archimaredes Oct 22 '21 at 11:48
  • @AndriyShevchenko I mean, necessarily I think I'd need to merge them as abstract objects...? – Archimaredes Oct 22 '21 at 11:49

1 Answers1

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.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • thank you! I also like that I can just `json1.ToObject()` 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!) – Archimaredes Oct 22 '21 at 12:09