【发布时间】:2018-06-22 18:48:49
【问题描述】:
我有这个 JSON 格式的字符串:
{
"hr": "12:56",
"vs": [
{
"pre": "73833",
"a": true,
"posx": "-46.688962875",
"posy": "-23.632046625"
},
{
"pre": "73722",
"a": true,
"posx": "-46.773388125",
"posy": "-23.68939025"
}
]
}
我想将 JSON 反序列化为此类:
public class Tracking
{
[JsonProperty(PropertyName = "hr")]
public string Hour { get; set; }
[JsonProperty(PropertyName = "vs")]
public IList<Vehicle> Vehicles { get; set; }
}
Vehicle 类目前具有以下属性:
public class Vehicle
{
[JsonProperty (PropertyName = "pre")]
public string Prefix {get; set; }
[JsonProperty (PropertyName = "posx")]
public string Y {get; set; }
[JsonProperty (PropertyName = "posy")]
public string X {get; set; }
}
相反,我想将posx 和posy 属性反序列化为一个名为Position 的子类,并带有X 和Y 属性:
public class Position
{
[JsonProperty (PropertyName = "posx")]
public string Y {get; set; }
[JsonProperty (PropertyName = "posy")]
public string X {get; set; }
}
导致以下Vehicle类:
public class Vehicle
{
[JsonProperty (PropertyName = "pre")]
public string Prefix {get; set; }
public Position Position {get; set; }
}
我打算在我系统上的更多地方使用Position 类,并且不想重复这些属性。但是使用新结构反序列化时,Position 属性返回 null。
{
"hr": "13:08",
"vs": [
{
"pre": "73833",
"a": true,
"Position": null
},
{
"pre": "73722",
"a": true,
"Position": null
}
]
}
我该怎么做才能使这段代码正常工作?
【问题讨论】:
-
反序列化什么?我想我们需要看看你想要反序列化的 json 是怎样的
-
更新问题
-
您应该将序列化部分与程序的其余部分分开。如果您想更改对象层次结构,请制作一个适配器,否则您很快就会在 hack 上苦苦挣扎以获得想要的 json 格式。最好将两者分开。
标签: c# asp.net json asp.net-web-api json.net