[英]How to convert from List<object> to List<T> in c#?
I have a Class:我有一个 Class:
public class Element
{
public List<object> objects { get; set; }
}
And a Class:还有一个 Class:
public class Node
{
public long id { get; set; }
}
I pass in a List<object> nodes
.我传入一个
List<object> nodes
。 So is there any way I can convert those List<object> objects
to List<Node> nodes
?那么有什么方法可以将这些
List<object> objects
转换为List<Node> nodes
?
I tried this way but it doesn't work List<Node> nodes = objects.Select(s => (nodes)s).ToList();
我试过这种方式,但它不起作用
List<Node> nodes = objects.Select(s => (nodes)s).ToList();
Try this: where listObject is the List<object>
试试这个:其中 listObject 是
List<object>
List<Node> newlist = listObject.Cast<Node>().ToList();
Your JSON is this:你的 JSON 是这样的:
{ "type": "way",
"id": 1000828751,
"nodes": [
9238280575,
9238280590,
9238280589,
9238280576,
9238280592,
9238280577,
9238280578,
9238280575
],
"tags": {
"amenity": "fire_station",
"name": "Đội Cảnh sát PCCC & CNCH quận Long Biên"
}
}
When I use https://json2csharp.com to create the C# classes I get this:当我使用https://json2csharp.com创建 C# 类时,我得到了这个:
public class Root
{
public string type { get; set; }
public int id { get; set; }
public List<object> nodes { get; set; }
public Tags tags { get; set; }
}
public class Tags
{
public string amenity { get; set; }
public string name { get; set; }
}
And that does successfully deserialize your JSON, but that's where you're at, trying to convert List<object>
to List<long>
.这确实成功地反序列化了您的 JSON,但这就是您所在的位置,尝试将
List<object>
转换为List<long>
。 However, the tool could have done better had it defined nodes
like this:但是,如果它像这样定义
nodes
,该工具可能会做得更好:
public class Root
{
...
public List<long> nodes { get; set; }
...
}
That now works without any further code changes.现在无需任何进一步的代码更改即可工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.