我创建了List<Dictionary<string, Dictionary<string,string>>>
的列表,我正在尝试在该列表中添加值。 PFB代码。
public string Get(Hello request)
{
string html= "[{'Id':1},{'Id':2}]";
List<Dictionary<string, Dictionary<string,string>>> lsData = null;
var values = JsonConvert.DeserializeObject<List<object>>(html); //parse json Array
for (int i = 0; i < values.Count; i++) // loop one element on json array and parse it.
{
var obj = values[i];
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(obj.ToString());
lsData.Add(i, data); //Showing error here
}
return "success";
}
但此代码显示以下错误。The type arguments for method 'ServiceStack.ServiceRoute Extensions.Add<T>(ServiceStack.Web.IService Routes, strong, ServiceStack.ApplyTo, params System.Linq.Expressions.Expression<System.Func<T,object>>[])' cannot be inferred from the usage. Try specifying the type arguments explicitly.
我不明白为什么会出现错误。提前谢谢。
答案 0 :(得分:2)
问题出在此行lsData.Add(i, data);
,因为您尝试将Dictionary<string, Dictionary<string,string>>
添加到给定列表,现在它需要两件事:
已初步化Dictionary<string,string>
,您正在按以下方式执行此操作:
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(obj.ToString());
假设Deserialization
正常工作,但是当你进行列表添加调用时,它的错误就像是为Dictionary
而不是List
添加值,因此请关注变化:
在for循环中添加以下代码:
var lsDataDictionary = new Dictionary<string, Dictionary<string,string>>();
lsDataDictionary.Add(i.ToString(),data)
lsData.Add(lsDataDictionary);
请注意,lsDataDictionary
键是字符串,for loop counter
需要转换为string
答案 1 :(得分:0)
您需要实例化lsData
lsData = new List<Dictionary<string, Dictionary<string,string>>>();