Javascript 将带有列表的JS对象转换为C#list
我的客户向我发送的对象如下:Javascript 将带有列表的JS对象转换为C#list,javascript,c#,json,parsing,dynamic,Javascript,C#,Json,Parsing,Dynamic,我的客户向我发送的对象如下: "content": { "title": "data title", "values": { "25": "some description", "26": "some info", "27": "some text", "28": "some other data", "29": "more info", "30": "more text",
"content": {
"title": "data title",
"values": {
"25": "some description",
"26": "some info",
"27": "some text",
"28": "some other data",
"29": "more info",
"30": "more text",
"31": "and another more description"
}
}
public static List<MyKeyValuePair> GetClientValues(dynamic content)
{
var myList = new List<MyKeyValuePair>();
try
{
foreach (PropertyInfo pi in content.values.GetType().GetProperties())
{
var value = "";
myList.Add(new MyKeyValuePair() { Id = int.Parse(pi.Name), Description = pi.GetValue(value, null).ToString() });
}
}
catch { }
return myList;
}
我需要将值
保存在C#列表
对象上。
我试图获取并保存这些值,如下所示:
"content": {
"title": "data title",
"values": {
"25": "some description",
"26": "some info",
"27": "some text",
"28": "some other data",
"29": "more info",
"30": "more text",
"31": "and another more description"
}
}
public static List<MyKeyValuePair> GetClientValues(dynamic content)
{
var myList = new List<MyKeyValuePair>();
try
{
foreach (PropertyInfo pi in content.values.GetType().GetProperties())
{
var value = "";
myList.Add(new MyKeyValuePair() { Id = int.Parse(pi.Name), Description = pi.GetValue(value, null).ToString() });
}
}
catch { }
return myList;
}
公共静态列表GetClientValues(动态内容)
{
var myList=新列表();
尝试
{
foreach(content.values.GetType().GetProperties()中的PropertyInfo pi)
{
var值=”;
Add(新的MyKeyValuePair(){Id=int.Parse(pi.Name),Description=pi.GetValue(value,null.ToString()});
}
}
捕获{}
返回myList;
}
但是在foreach
行中,我收到了以下错误消息:
“System.Collections.Generic.Dictionary.values”是
由于其保护级别而无法访问
如何解决此问题?如果已键入动态,您应该能够执行以下操作:
public static List<MyKeyValuePair> GetClientValues(dynamic content)
{
var myList = new List<MyKeyValuePair>();
foreach (var kv in content["values"])
{
myList.Add(new MyKeyValuePair {
Id = int.Parse(kv.Key),
Description = kv.Value
});
}
return myList;
}
公共静态列表GetClientValues(动态内容)
{
var myList=新列表();
foreach(内容[“值”]中的var kv)
{
myList.Add(新的MyKeyValuePair){
Id=int.Parse(千伏键),
说明=千伏值
});
}
返回myList;
}
否则,您可能需要反序列化输入json字符串。如果您使用visual studio 2013及更高版本,请复制此json并使用“编辑”菜单下的“粘贴json为类”从中生成一个类,但是,如果您使用的是较低版本的VS,您仍然可以键入类结构,然后下一步就是使用newtonsoft json将json反序列化到上面创建的类中 谢谢@styfle!使用该代码时,我也收到了相同的错误消息,但我将我的
foreach
行更改为foreach(var kv in content[“values”])
,现在它工作得很好。非常感谢你