C#反序列化Json未知密钥 [英] C# deserialize Json unknown keys

查看:255
本文介绍了C#反序列化Json未知密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JSON,我必须反序列化它:

I have this JSON and i have to deserialize it:

{
  "homepage": "http://files.minecraftforge.net/maven/net/minecraftforge/forge/",
  "promos": {
    "1.10-latest": "12.18.0.2000",
    "1.10.2-latest": "12.18.1.2014",
    "1.10.2-recommended": "12.18.1.2011",
    "1.5.2-latest": "7.8.1.738",
    "1.5.2-recommended": "7.8.1.737",
    "1.6.1-latest": "8.9.0.775",
    "1.6.2-latest": "9.10.1.871",
    "1.6.2-recommended": "9.10.1.871",
    "1.6.3-latest": "9.11.0.878",
    "1.6.4-latest": "9.11.1.1345",
    "1.6.4-recommended": "9.11.1.1345",
    "1.7.10-latest": "10.13.4.1614",
    "1.7.10-latest-1.7.10": "10.13.2.1343",
    "1.7.10-recommended": "10.13.4.1558",
    "1.7.2-latest": "10.12.2.1147",
    "1.7.2-recommended": "10.12.2.1121",
    "1.8-latest": "11.14.4.1577",
    "1.8-recommended": "11.14.4.1563",
    "1.8.8-latest": "11.15.0.1655",
    "1.8.9-latest": "11.15.1.1902",
    "1.8.9-recommended": "11.15.1.1722",
    "1.9-latest": "12.16.0.1942",
    "1.9-recommended": "12.16.1.1887",
    "1.9.4-latest": "12.17.0.1990",
    "1.9.4-recommended": "12.17.0.1976",
    "latest": "12.18.1.2014",
    "latest-1.7.10": "10.13.2.1343",
    "recommended": "12.18.1.2011"
  }
}

在这个网站上进行了大量搜索,我得到了以下代码:

Searching on this website a lot, i came out with this code:

dynamic json = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
foreach (KeyValuePair<string, string> entry in json["promos"])
{
    MessageBox.Show(entry.Key);
    MessageBox.Show(entry.Value);
}

我需要从该Json中获取键和值,但是使用此代码,它说在第3行pos 13处有一个意外的字符. 我尝试了很多不同的方式,但是我无法同时获得价值和关键.通过一些代码,我仅获得了密钥,而通过其他代码,我仅获得了价值.您能解释一下如何同时获得价值和关键吗?

I need to get both Key and Value from that Json but with this code it says there is an unexpected character on line 3 pos 13. I tried in a lot of different ways but i can't get value and key at the same time. With some code i got just the key and with some other code i got just the value. Can you explain me how to obtain both value and key?

推荐答案

您可以将json直接解析为JObject并将节点"promos"转换为Dictionary

You can directly parse the json as JObject and convert the node "promos" to Dictionary

var json = JObject.Parse(data);
var promos = json["promos"].ToObject<Dictionary<string, string>>();
foreach (var entry in promos)
{
    MessageBox.Show(entry.Key);
    MessageBox.Show(entry.Value);
}

这篇关于C#反序列化Json未知密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆