其他分享
首页 > 其他分享> > Newtonsoft助手类

Newtonsoft助手类

作者:互联网

属性替换:

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
}

标签:Newtonsoft,replaceProp,replaceObject,JObject,助手,var,new,null
来源: https://www.cnblogs.com/fanfan-90/p/15694299.html