我有一个方法:
public object getData()
{
//make an external call
}
执行getData()
时,我们得到一个如下所示的对象:
{
"Location":
{
"LocationID":1,
"ABCIsCopperFiberNidBit":0,
"ABCCopperJunctionID":0,
"ABCFiberJunctionID":0,
"ABCGrade":0,
"ABCCopperDSLAMDistance":0
}
}
从上面我需要将其转换为具体的数据类型
,例如List
这些:
public class LocationModel
{
public int locationId{get;set;}
public string key {get;set;}
public string value {get;set;}
}
我要找的结果是List<LocationModel>
:
locationid=1,
key=ABCIsCopperFiberNidBit,
value=0
locationid=1
key = ABCCopperJunctionID,
value=0
等
如何从此对象转换为所需的强类型数据类型?
我的问题不是为了你为我做的工作。我是一位经验丰富的开发人员,我无法深入研究完成此任务的各种方法。
答案 0 :(得分:3)
像Json.NET这样的东西会很好用:
string json = @"{
""Location"":
{
""LocationID"":1,
""ABCIsCopperFiberNidBit"":0,
""ABCCopperJunctionID"":0,
""ABCFiberJunctionID"":0,
""ABCGrade"":0,
""ABCCopperDSLAMDistance"":0
}
}";
然后:
var obj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var loc = obj["Location"];
var locid = loc["LocationID"].Value<int>();
var list = new List<LocationModel>();
foreach(var prop in loc.Children().OfType<JProperty>())
{
if (prop.Name == "LocationID") continue;
list.Add(new LocationModel
{
locationId = locid,
key = prop.Name,
value = prop.Value.ToString()
});
}