用其他字符串替换JSON的一部分(使用字符串令牌) [英] Replace part of a JSON with other (using a string token)

查看:98
本文介绍了用其他字符串替换JSON的一部分(使用字符串令牌)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个无法解决的问题,我在不同的地方搜寻,但是我仍然找不到它.

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查询语法.它返回与所选项目的相对应的JToken,如果找不到,则返回null.该JToken依次具有 Replace(JToken replacement) 方法.因此,您可以执行以下操作:

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的一部分(使用字符串令牌)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆