Json.net rename properties

前端 未结 2 1570
盖世英雄少女心
盖世英雄少女心 2020-12-06 01:56

I have a string representing JSON and I want to rename some of the properties using JSON.NET. I need a generic function to use for any JSON. Something like:

         


        
2条回答
  •  时光取名叫无心
    2020-12-06 02:53

    We use this approach. You can find the property you want using JObject's SelectToken(). Yes it does support JsonPath.

    public static class NewtonsoftExtensions
    {
        public static void Rename(this JToken token, string newName)
        {
            var parent = token.Parent;
            if (parent == null)
                throw new InvalidOperationException("The parent is missing.");
            var newToken = new JProperty(newName, token);
            parent.Replace(newToken);
        }
    }
    

提交回复
热议问题