[英]C# json parse string inside multiple curly brackets with case-insensitive
我想从网站上解析: http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json
使用本网站以获得更好的视图。 当我输入 Aatrox 时,我想检索 266
到目前为止,我设法做到了,但它区分大小写。 有没有办法让我的代码不区分大小写?
var input = new WebClient().DownloadString(@"http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json");
var obj = JObject.Parse(input);
var input= obj["data"]["Aatrox"]["key"];
更新代码
var input = new WebClient().DownloadString(@"http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json");
JObject json = (JObject)JsonConvert.DeserializeObject(input);
Dictionary<string, object> d = new Dictionary<string, object>(json.ToObject<IDictionary<string, object>>(), StringComparer.CurrentCultureIgnoreCase);
String f = d["data"]["Aatrox"]["key"].ToString();
它仍然无法正常工作。
我认为您可以使用 Dictionary 而不是匿名 object,请参阅此答案
更新:
public class InsensitiveWrapper
{
private readonly JObject _rWrapped;
private readonly string _rLeafValue;
public InsensitiveWrapper(JObject jsonObj)
{
_rWrapped = jsonObj ?? throw new ArgumentNullException(nameof(jsonObj));
}
private InsensitiveWrapper(string value)
{
_rLeafValue = value ?? throw new ArgumentNullException(nameof(value));
}
public string Value => _rLeafValue ?? throw new InvalidOperationException("Value can be retrieved only from leaf.");
public InsensitiveWrapper this[string key]
{
get
{
object nonTyped = _rWrapped.GetValue(key, StringComparison.OrdinalIgnoreCase);
if (nonTyped == null)
throw new KeyNotFoundException($"Key {key} is not found.");
JObject jObject = nonTyped as JObject;
if (jObject == null)
return new InsensitiveWrapper(nonTyped.ToString());
return new InsensitiveWrapper(jObject);
}
}
}
public static async Task Main()
{
var input = new WebClient().DownloadString(@"http://ddragon.leagueoflegends.com/cdn/10.9.1/data/en_US/champion.json");
JObject json = (JObject)JsonConvert.DeserializeObject(input);
var dictionary = new InsensitiveWrapper(json);
var val = dictionary["data"]["Aatrox"]["key"].Value;
Console.WriteLine(val);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.