2

I have JSON objects that I want to concatenate into one JSON object.

How do I do that using NewtonSoft's JSON package?

theDmi
  • 17,546
  • 6
  • 71
  • 138
sireesha
  • 147
  • 1
  • 5
  • 16
  • 1
    Seems the same as http://stackoverflow.com/questions/14121010/merge-two-json-net-jtokens – Peter Ritchie Oct 06 '14 at 18:05
  • use the link http://stackoverflow.com/questions/21160337/how-can-i-merge-two-jobject/21236171#21236171 – Dibu Oct 28 '14 at 11:50
  • @PeterRitchie Related, but not a duplicate. The other question is specifically about merging arrays by concatenating them. I updated the title on that question to make this clear (before this was only mentioned in the question text). – theDmi Aug 12 '16 at 13:33

1 Answers1

6

Use JContainer.Merge().

The logic for combining JSON objects together is fairly simple: name/values are copied across, skipping nulls if the existing property already has a value.

Json.NET 6.0 Release 4

Example:

var jObject1 = // Your first json object as JObject
var jObject2 = // Your second json object as JObject 

jObject1.Merge(jObject2);

// jObject1 contains now the merged properties from jObject2.

Note that for properties that exist in both objects, the jObject2 ones take precedence (i.e. overwrite the properties in jObject1).

theDmi
  • 17,546
  • 6
  • 71
  • 138