Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

c# - Replace part of a JSON with other (using a string token)

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': 'asd@asd.com', 'phone': '',  'birthday': '', 'married': false, 'spouse': {'name': '', 'lastname': ''} } }";

var json2 = @" {'client': {'name': 'aaaa', 'lastname': 'bbbb', 'email': 'cccccc@ccccc.com',  '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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...