C# 如何在codebehind中处理json对象

C# 如何在codebehind中处理json对象,c#,asp.net,json,jquery,C#,Asp.net,Json,Jquery,我有-var JsonObj=[]item as Dictionary)。SelectMany(d=>d)。ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value); 有一个非常灵活的json框架(json.NET)可以帮助您实现这一点,如果您在json上做了大量工作,那么确实值得考虑一下您为什么要使用对象而不是自定义的强类型DTO-like Person,员工等等?如果你想将所有数据合并到一个词典中,你可以先将单个项目合并到一个词典中。

我有-
var JsonObj=[]JQuery.ajax()
方法将其发送给codebehind。我能够在一个方法中接收到这样的参数

[WebMethod]
public static void SaveInfo(List<Object> userEnteredDetails)
{
}
[WebMethod]
公共静态void SaveInfo(列出用户输入的详细信息)
{
}
我在收集过程中循环得到类似这样的数据

foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
}
foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
string city= details["city"] as string;
}
foreach(userEnteredDetails中的对象项)
{
字典详细信息=作为字典的项目;
字符串名称=作为字符串的详细信息[“customerName”];
}
问题是,我收到的收藏品超过10件。因此,我无法读取上述for循环中的另一个属性。像这样的,

foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
}
foreach (object item in userEnteredDetails)
{
Dictionary<string, object> details = item as  Dictionary<string, object>;

string name = details["customerName"] as string;
string city= details["city"] as string;
}
foreach(userEnteredDetails中的对象项)
{
字典详细信息=作为字典的项目;
字符串名称=作为字符串的详细信息[“customerName”];
字符串city=详细信息[“city”]作为字符串;
}

第一次城市将抛出一个错误,下次客户名称。因为item变量一次只有一个变量。如何高效地读取所有10条以上的记录,因为我们没有属性,但只能通过索引器(详细信息[“customerName]”)读取。有一件事,您可以使用一个类型,其中的字段映射到对象列表。在进行ajax调用时,将json对象字符串化。在web方法中,将其作为字符串接收。使用Json反序列化程序并将其反序列化为您创建的类型。

尝试以下操作:

string name = String.Empty;
string city = String.Empty;
foreach (object item in userEnteredDetails)
{
 Dictionary<string, object> details = item as  Dictionary<string, object>;
if (details.ContainsKey("customerName"))
 name = details["customerName"] as string;
if (details.ContainsKey("city"))
 city= details["city"] as string;
}
string name=string.Empty;
string city=string.Empty;
foreach(userEnteredDetails中的对象项)
{
字典详细信息=作为字典的项目;
if(详细信息。ContainsKey(“客户名称”))
名称=详细信息[“客户名称”]作为字符串;
if(详细信息。集装箱(“城市”))
城市=详细信息[“城市”]作为字符串;
}

您可以枚举详细信息字典

foreach(var kvp in details)
  {
// do something with kvp.Key and kvp.Value
  }
编辑: 要首先获取一个合并的详细信息词汇表,您可以尝试以下操作:

var details = list.Select(item => item as Dictionary<string, object>).SelectMany(d => d).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
var details=list.Select(项=>item as Dictionary)。SelectMany(d=>d)。ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value);

有一个非常灵活的json框架(json.NET)可以帮助您实现这一点,如果您在json上做了大量工作,那么确实值得考虑一下您为什么要使用
对象而不是自定义的强类型DTO-like Person,员工等等?如果你想将所有数据合并到一个词典中,你可以先将单个项目合并到一个词典中。