C# deserialize Json unknown keys

妖精的绣舞 提交于 2019-12-04 07:57:05

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);
}

The issue is the type you're trying to deserialize into. You're trying to deserialize it as a Dictionary, but while the first entry is a pair of string, promos is a Dictionary itself, so you can't cast the value of "promos" to string! Supposing your json is in a file called "json.json" you can obtain a Dictionary by iterating through promos JObject and cast the items you obtain to a JProperty, in this way:

var json = File.ReadAllText("json.json");
var deserialized = JsonConvert.DeserializeObject<JObject>(json);

var dictionary = new Dictionary<string, string>();

foreach (JProperty item in deserialized["promos"])
    dictionary.Add(item.Name, item.Value.ToString());

Your data is not a Dictionary<string, string> because the value of promos is not a string but a Dictionary.

You could deserialize to an JObject and then get the value of your promos property.

JObject json = JsonConvert.DeserializeObject<JObject>(data);
//var promos = json.Value<Dictionary<string, string>>("promos");
var promos = data["promos"].ToObject<Dictionary<string, string>>();
foreach (KeyValuePair<string, string> entry in promos) {
   //do some stuff
}

EDIT

Not sure, why the original way does not work and don't have the time right now to investigate, but the second line should do it.

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