With json.net, is there a shortish way to manipulate all string fields?

后端 未结 1 425
轮回少年
轮回少年 2020-12-12 01:01

Given an arbitrary Newtonsoft.Json.Linq.JObject, if you want to apply some function to all string values that appear in it (wherever that may be) - whether as a basic value

相关标签:
1条回答
  • 2020-12-12 01:39

    One simple way to do this is to use JContainer.DescendantsAndSelf() to find all descendants of the root JObject that are string values, then replace the value with a remapped string using JToken.Replace():

    public static class JsonExtensions
    {
        public static JToken MapStringValues(this JContainer root, Func<string, string> func)
        {
            foreach (var value in root.DescendantsAndSelf().OfType<JValue>().Where(v => v.Type == JTokenType.String).ToList())
                value.Replace((JValue)func((string)value.Value));
            return root;
        }
    }
    

    Then use it like:

    jObj.MapStringValues(s => "remapped " + s);
    
    0 讨论(0)
提交回复
热议问题