我目前正在开发.NET Framework 4.7.2应用程序。从Web服务响应中,我需要将JSON数据解析为List<KeyValuePair<int, Dictionary<string, object>>>
。此数据类型对于进一步的程序流程很重要,我无法更改。
具有动态属性的JSON数据如下所示:
{ "data" : [
{"Id":1, Text:"Test1", coolProp: 213 },
{"Id":2, Text:"Test2"},
{"Id":3, Text:"Test3", otherProp: "cool" },
]}
我尝试了以下编码,但是没有用:
JsonConvert.DeserializeObject<List<KeyValuePair<int, Dictionary<string, object>>>>(Convert.ToString(JObject.Parse(json)["data"]));
另一方面,我可以将json转换为ExpandoObject:
var expando = JsonConvert.DeserializeObject<List<ExpandoObject>>(Convert.ToString(JObject.Parse(json)["data"]));
我正在考虑编写一个私有方法来转换
将o将对象展开到我的List<KeyValuePair<int, Dictionary<string, object>>>
中。
private KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>> ConvertExpandoToKeyValue(float key, List<ExpandoObject> expando)
{
var result = new KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>>();
// I don't really know how to convert the expando object to the desired data structure
// Moreover I need to put a float key in the structure: 52.2343
return result;
}
ExpandoObject看起来像这样:
KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>>
的最终结果应如下所示:
您知道如何将ExpandoObject转换为所需的数据类型并在开头添加密钥吗?
也许,您是否知道将JSON数据转换为所需数据结构的更好方法?
非常感谢您!
答案 0 :(得分:1)
好的,我写了一个解决方案,我只想与您分享。也许有更好的方法:
private KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>> ConvertExpandoToKeyValue(float key, List<ExpandoObject> expando)
{
var result = new KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>>
(key, new List<KeyValuePair<int, Dictionary<string, object>>>());
for (int i = 0; i < expando.Count; i++)
{
var element = new Dictionary<string, object>(expando[i]);
var propertyValues = new KeyValuePair<int, Dictionary<string, object>>(i, element);
result.Value.Add(propertyValues);
}
return result;
}