属性替换:
public static void Replace(JObject jsonObject, JObject replaceObject)
{
if (jsonObject != null && replaceObject != null)
{
foreach (JProperty replaceProp in replaceObject.Children())
{
if (replaceProp.HasValues && replaceProp.Type == JTokenType.Property)
{
var jsonToken = jsonObject.SelectToken(replaceProp.Value.Path);
if (jsonToken != null)
{
jsonToken.Replace(replaceProp.Value);
}
}
}
}
}
Demo:
var replaceobj = JObject.FromObject(new { a = 2, b = "3", c = new { d = "4" } });
var jobj = JObject.FromObject(new { a = 1, b = "2", c = new { d = "3", e = new object[] { new { f = "4" } } }, g = 5 });
Replace(jobj, replaceobj);
结果:
{
"a": 2,
"b": "3",
"c": {
"d": "4"
},
"g": 5
}