How to change all keys to lowercase when parsing JSON to a JToken

末鹿安然 提交于 2019-11-29 14:00:18

One possible way to solve this with minimal code is to subclass the JsonTextReader and override the Value property to return a lowercase string whenever the current TokenType is PropertyName:

public class LowerCasePropertyNameJsonReader : JsonTextReader
{
    public LowerCasePropertyNameJsonReader(TextReader textReader)
        : base(textReader)
    {
    }

    public override object Value
    {
        get
        {
            if (TokenType == JsonToken.PropertyName)
                return ((string)base.Value).ToLower();

            return base.Value;
        }
    }
}

This works because the underlying JsonTextReader keeps the TokenType updated as its internal state changes, and the serializer (actually the JsonSerializerInternalReader class) relies on that when it goes to retrieve the property name from the reader via the Value property.

You can create a short helper method to make it easy to deserialize using the custom reader:

public static class JsonHelper
{
    public static JToken DeserializeWithLowerCasePropertyNames(string json)
    {
        using (TextReader textReader = new StringReader(json))
        using (JsonReader jsonReader = new LowerCasePropertyNameJsonReader(textReader))
        {
            JsonSerializer ser = new JsonSerializer();
            return ser.Deserialize<JToken>(jsonReader);
        }
    }
}

Then in your code, just replace this:

JToken json = JToken.Parse(jsonString);

with this:

JToken json = JsonHelper.DeserializeWithLowerCasePropertyNames(jsonString);

Fiddle: https://dotnetfiddle.net/A0S3I1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!