获取对ArrayList对象的访问 [英] Getting access to ArrayList object
问题描述
我正在开发一个读取一些JSON数据并进行一些统计的应用程序,但是现在我遇到了问题.
I'm developing an application that reads some JSON data and makes some statistics, but now I've run into a problem.
我有一个像这样的字符串:
I have a string like this:
{
"position":[
{
"someKey1":"someVal1",
"someKey2":"someVal2",
},
{
"someKey1":"someVal3",
"someKey2":"someVal4",
}
}
我想访问someKeys和someValues.
I want to access the someKeys and someValues.
我正在将其转换成这样的字典:
I'm converting it to a dictionary like this:
Dictionary<string, object> values = deserializeJSON(json_string);
很抱歉,忘记添加deserializeJSON:
Edit 1: Sorry, forgot to add deserializeJSON:
private Dictionary<string, object> deserializeJSON(string p_jsonObject)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<Dictionary<string, dynamic>>(p_jsonObject);
}
现在,我无法使用键"position"访问值列表.如果我尝试打印值的类型["position"],我会得到:
Now I have trouble getting access to the list of values with the key "position". If I try to print the type of values["position"] I get:
System.Collections.ArrayList
所以我以为我可以反复进行此操作,但我不能.我尝试使用枚举器(在这里读到,它将可以遍历对象,并且必须将其添加到ArrayList中以进行强制转换):
So I thought I could just iterate through this, but I can't. I tried using enumerator (read in here that it would make it possible to iterate over the objects, and that I have to add it to an ArrayList to cast it):
ArrayList arr = new ArrayList();
IEnumerable enumerable = values["position"] as IEnumerable;
foreach (object element in enumerable)
{
arr.Add(element);
}
当我打印arr [0]时,我得到:
When I print arr[0] I get:
System.Collections.Generic.Dictionary`2[System.String,System.Object]
在这里我很困惑.我假设这是someKeys和someVals的列表,应该正确,对吧? 现在,我很幸运地尝试访问这些值.我尝试了arr [0] ["someKey1"],但收到一个错误,我无法将索引应用于对象".
Here I'm confused. I assume it's the list of someKeys and someVals, which should be correct, right? Now I've tried, with no luck, getting access to these values. I tried arr[0]["someKey1"] but get an error that I cannot apply indexing to 'object'.
对解决方案有何想法?理想的解决方案更理想吗? :)
Any ideas on a solution? Ideally a more elegant solution? :)
预先感谢
推荐答案
您可以使用 Linq到JSON (从NuGet添加Newtonsoft的JSON.NET):
You can use Linq to JSON (add Newtonsoft's JSON.NET from NuGet):
JObject jo = JObject.Parse(json);
var value = (string)jo["position"][1]["someKey1"]; // someVal3
另一个示例:
JObject jo = JObject.Parse(json);
JArray positions = (JArray)jo["position"];
foreach (var item in positions)
{
// use (string)item["someKey1"]
// use (string)item["someKey2"]
}
这篇关于获取对ArrayList对象的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!