我有一个无法解决的问题,我在不同的地方寻找和寻找,但我仍然没有找到它.
I'm having an issue that I cant fix, I seek and seek in different places, but I still without find it.
查看此代码:
//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;
我需要使用字符串而不是o1.client.email"来替换内容.因为可以是任何东西.(json也可以是任何东西)
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 有效,但我丢失了日期、布尔值或数字时的数据类型)
(XML works, but I lost the data type when is a date, boolean or numeric)
NetFiddle 中的示例.
可以使用SelectToken
选择 JSON 对象层次结构中的任何项目.它支持 JSONPath 查询语法.它返回一个与所选项目的 value 对应的 JToken
,如果没有找到,则返回 null
.该 JToken
又具有 Replace(JToken替换)
方法.因此你可以这样做:
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));
这篇关于将部分 JSON 替换为其他(使用字符串标记)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!