本文介绍了JSON.NET JToken密钥是否区分大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用JSON.NET执行一些自定义反序列化,我只是发现它会将JToken中的键值视为区分大小写.这是一些代码:

I'm having to perform some custom deserialization with JSON.NET and I just found that it's treating the key values in a JToken as case sensitive. Here's some code:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
     JToken token = JToken.Load(reader);
     JToken version = token["version"];

     string ver = version.ToObject<string>();

     return new MyVersion(ver);
}

version变量为null,即使json在顶层包含一个version元素,也只是大写:

The version variable is null even though the json contains a version element at the top level, it's just in upper case:

{
    "VERSION" : "1.0",
    "NAME" : "john smith"
}

是否可以使用不区分大小写的键使用JToken?还是没有JToken的另一种方法可以让我获取和反序列化单个属性?

Is there any way to use JToken with case-insensitive keys? Or maybe another approach without JToken that lets me grab and deserialize individual properties?

根据评论,我最终这样做:

Based on the comments I ended up doing this:

JObject token = JObject.Load(reader);
string version = token.GetValue("version", StringComparison.OrdinalIgnoreCase).ToObject<string>(serializer);

推荐答案

您可以将JToken强制转换为JObject并执行以下操作:

You can cast JToken to JObject and do this:

string ver = ((JObject)token).GetValue("version", StringComparison.OrdinalIgnoreCase)?.Value<string>();

这篇关于JSON.NET JToken密钥是否区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 10:34