10

I'm having an issue that I cant fix, I seek and seek in different places, but I still without find it.

See this code:

//I have 2 json to merge  

var json = @"{'client': {'name': 'Should NO CHANGE', 'lastname': '', 'email': '[email protected]', 'phone': '',  'birthday': '', 'married': false, 'spouse': {'name': '', 'lastname': ''} } }";

var json2 = @" {'client': {'name': 'aaaa', 'lastname': 'bbbb', 'email': '[email protected]',  'phone': '', 'birthday': '', 'married': false,  'spouse': {'name': 'dddddd', 'lastname': 'eeeee'} } } ";

//for example to properties to replace
var path = "client.spouse";
var path2 = "client.email";

dynamic o1 = JObject.Parse(json);
dynamic o2 = JObject.Parse(json2);



//I want this, but using the string (LIKE REFLECTION) 
// NOT THE DYNAMIC object 
// Can be a simple property or a complex object
o1.client.spouse = o2.client.spouse;
o1.client.email = o2.client.email; 

I need to use a string instead of "o1.client.email" to replace the content. Because can be anything. (also the json can be anything)

I can replace by strings, by dynamic, or whatever it work.

(XML works, but I lost the data type when is a date, boolean or numeric)

Example in NetFiddle.

12
  • Does String.Replace work? Commented Oct 9, 2015 at 18:51
  • @EmpereurAiman it is well known that String replace does not work :) Commented Oct 9, 2015 at 18:51
  • I don't understand the question well, but if you want to replace client.email with a string, o1.client.email = "yourString"; works. Commented Oct 9, 2015 at 18:56
  • o1["client"]["email"]? JObject and JToken. Commented Oct 9, 2015 at 18:57
  • 2
    Are you looking for o1.client.email = o2.SelectToken("client.email"); ? Commented Oct 9, 2015 at 19:32

1 Answer 1

34

You can use SelectToken to select any item in the JSON object hierarchy. It supports JSONPath query syntax. It returns a JToken corresponding to the value of the selected item, or null if not found. That JToken in turn has a Replace(JToken replacement) method. Thus you can do:

var o1 = JObject.Parse(json);
var o2 = JObject.Parse(json2);

var path = "client.spouse";
o1.SelectToken(path).Replace(o2.SelectToken(path));

var path2 = "client.email";
o1.SelectToken(path2).Replace(o2.SelectToken(path2));
Sign up to request clarification or add additional context in comments.

2 Comments

This was exactly what I need ! VERY VERY THANKS !
Note, be careful as this only works if the item exists. If the item does not exist, SelectToken returns null and you'll need to change your strategy.

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.