我有以下json:
var x = [
[99,"abc","2dp",{"Group": 0,"Total":[4, 1]}],
[7,"x","date"],
[60,"x","1dp",{"Group": 1}],
...
]
我需要对这个json进行反序列化,但我在字段3中遇到了对象的问题。这是第一次尝试:
string x = "[[99,\"abc\",\"2dp\",{\"Group\": 0,\"Total\":[4, 1]}],[7,\"x\",\"date\"],[60,\"x\",\"1dp\",{\"Group\": 1}]]";
List<List<object>> xobj = JsonConvert.DeserializeObject<List<List<object>>>(x);
这似乎有效。在Visual Studio 2015中使用中间窗口:
xobj[0][0];
99
xobj[1][2];
"date"
但是我不确定如何访问字段3中的对象?
xobj[0][3];
{{
"Group": 0,
"Total": [
4,
1
]
}}
ChildrenTokens: Count = 2
Count: 2
First: {"Group": 0}
HasValues: true
Last: {"Total": [
4,
1
]}
Next: null
Parent: null
Path: ""
Previous: null
Root: {{
"Group": 0,
"Total": [
4,
1
]
}}
Type: Object
Results View: Expanding the Results View will enumerate the IEnumerable
Dynamic View: Expanding the Dynamic View will get the dynamic members for the object
xobj[0][3].Root["Group"];
error CS1061: 'object' does not contain a definition for 'Root' and no extension method 'Root' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
我注意到它有一个&#39; First&#39;方法,所以我试过这个,但也没有运气:
xobj[0][3][0];
error CS0021: Cannot apply indexing with [] to an expression of type 'object'
那么如何访问每个列表对象中的值呢?
答案 0 :(得分:1)
如果您只想访问可选条目,请尝试以下方法:
static void Main(string[] args)
{
string x = "[[99,\"abc\",\"2dp\",{\"Group\": 0,\"Total\":[4, 1]}],[7,\"x\",\"date\"],[60,\"x\",\"1dp\",{\"Group\": 1}]]";
List<List<object>> xobj = JsonConvert.DeserializeObject<List<List<object>>>(x);
for (int i = 0; i < xobj.Count; i++)
{
// Do something with index 0 to 3
if (xobj[i].Count == 4)
{
// I have the optional entry with Group & Total properties
dynamic opt = xobj[i][3];
Console.WriteLine("GROUP: " + opt.Group); // Mandatory
Console.WriteLine("GROUP value: " + opt.Group.Value);
if (opt["Total"] != null)
{
Console.WriteLine("TOTAL: " + opt.Total);
Console.WriteLine("TOTAL item 0 value: " + opt.Total[0].Value);
Console.WriteLine("TOTAL item 1 value: " + opt.Total[1].Value);
}
}
}
Console.ReadLine();
}