我在标题中提到,json 反序列化不完全,因为某些对象在 Controller 中具有正确的值(我将 json 发送到 asp.net mvc 4 Controller ),但问题发生在存储在数组(准确的说,问题出现在Data上)
我有以下类(class):
public class Node
{
[JsonProperty("id")]
public int? Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
private Data _data = new Data();
[JsonProperty("data")]
public Data Data { get; set; }
private List<Adjacency> _adjacencies = new List<Adjacency>();
[JsonProperty("adjacencies")]
public List<Adjacency> Adjacencies
{
get { return _adjacencies; }
set { _adjacencies = value; }
}
private List<Instance> _dependendStates = new List<Instance>();
public List<Instance> DependentStates
{
get { return _dependendStates; }
set { _dependendStates = value; }
}
}
public class Data
{
[JsonProperty("$posX")]
public decimal PosX { get; set; }
[JsonProperty("$posY")]
public decimal PosY { get; set; }
}
public class Adjacency
{
[JsonProperty(PropertyName = "nodeTo")]
public string NodeTo { get; set; }
[JsonProperty(PropertyName = "data")]
public AdjData Data { get; set; }
//doesn't contain definition for automated transitions
}
public class AdjData
{
[JsonProperty(PropertyName = "$labelid")]
public string LabelId { get; set; }
[JsonProperty(PropertyName = "$labeltext")]
public string Label { get; set; }
[JsonProperty(PropertyName = "$type")]
public string Type { get; set; }
}
我已突出显示没有正确值的字段。
The null problem http://img19.imageshack.us/img19/530/36976913.png
json 看起来像这样:
{
"result":[
{
"id":"100",
"name":"Start",
"data":{
"$posX":-100,
"$posY":-100,
"$deployed":true,
"$color":"#000000",
"$selected":"true"
},
"adjacencies":[
{
"nodeTo":"188",
"data":{
"$type":"labeled_arrow",
"$labelid":"Label Name",
"$labeltext":"Label Name"
}
}
]
},
{
"id":"188",
"name":"Second ",
"data":{
"$dim":20,
"$color":"#000000",
"$selected":"true"
},
"adjacencies":[
]
}
],
"smName":"gftrds"
}
我在解决这个问题时遇到了问题,因为我不明白或不明白问题出在哪里。
最佳答案
免责声明:我无法准确地重现这一点,就像在我的例子中 Label
和 LabelId
反序列化得很好,尽管 Type
没有,所以我的答案可能无法解决您遇到的问题。
就我而言,如果 "$type":"labeled_arrow"
属性不是第一个属性,我只能反序列化它 - 如果它出现在 "$labelid"之后: “标签名称”
或 “$labeltext”:“标签名称”
效果很好。
奇怪的是,如果$type
属性在Json中被称为type
并被引用为[JsonProperty(PropertyName = "type")]
在 C# 中,无论顺序如何,它都可以很好地反序列化。
在您的情况下,您也无法反序列化 Label
或 LabelId
,因此您的问题可能是由其他原因引起的。为了排除我所建议的可能性,尝试修改一些属性名称(可能只是去掉 $)以查看它们是否导致属性被错误地反序列化可能是值得的。
关于asp.net-mvc-4 - 嵌套 json 反序列化不完全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13135394/