【发布时间】:2021-11-29 23:59:01
【问题描述】:
我有以下代码试图在字典中获取值,但似乎无法正常工作。
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace DemoTests
{
class Program
{
static void Main(string[] args)
{
string jsonString = "{\"Name\":\"Bob Smith\",\"mainTitle\":\"Title1\",\"emailList\":[\"test.e@example.com\"],\"rowCount\":\"4\",\"emailSubject\":\"Test Email\",\"items\":{\"sheets\":[[{\"ID\": \"4564342\", \"start\": \"08:00\"}]]}}";
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<dynamic, dynamic> results = jsonObj.ToObject<Dictionary<dynamic, dynamic>>();
List<dynamic> subList = results["items"]["sheets"].ToObject<List<dynamic>>();
foreach (dynamic tableEntries in subList)
{
var entryDict = tableEntries[0].ToObject<Dictionary<dynamic, dynamic>>();
for (int k = 0; k < entryDict.Keys.Count; k++)
{
String key = entryDict.Keys.ToList()[k];
Console.WriteLine(key);
}
}
}
}
}
我在String key = entryDict.Keys.ToList()[k]; 线上遇到错误
Exception thrown: 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' in System.Linq.Expressions.dll An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Linq.Expressions.dll 'System.Collections.Generic.Dictionary<object,object>.KeyCollection' does not contain a definition for 'ToList'
我怎样才能让它运行?我对 C# 很陌生,所以也愿意用更好的方法来编写我的代码
【问题讨论】:
-
最好只使用您已经解析的
JObject,而不是所有那些字典 -
@CamiloTerevinto 知道了。将更多地研究 JObject。我最初很难从中获取键列表,最后只是转换为字典
标签: c# dictionary generics tostring