我正在使用最新的(4.5)版本的Newtonsoft Json.Net来序列化我的WCF Web服务返回的复杂类型。出于某种原因,如果我应用[JsonProperty]
属性,则字段不会序列化:
[DataContract]
[JsonObject(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]
public class ScalarResult
{
[JsonProperty(Order = 0)]
public string QueryId { get; set; }
[JsonProperty(Order = 1)]
public float CurrentPeriodValue { get; set; }
[JsonProperty(Order = 2)]
public bool HasPriorValue { get; set; }
[JsonProperty(Order = 3)]
public float PriorPeriodValue { get; set; }
[JsonProperty(Order = 4)]
public float ChangeOverPrior { get; set; }
[JsonProperty(Order = 5)]
public float ChangeOverPriorPercent { get; set; }
这导致了一个吝啬的回归对象:
{
"SomethingElse": "why am I the only thing visible?"
}
如果我将[DataMember]
添加到每个字段(I'm not supposed to have to do,根据Json.NET文档),则会显示字段,但忽略(Order = x)
属性,我相信Json.NET可能实际上并没有进行序列化:
[DataContract]
[JsonObject(MemberSerialization = Newtonsoft.Json.MemberSerialization.OptIn)]
public class ScalarResult
{
[DataMember]
[JsonProperty(Order = 0)]
public string QueryId { get; set; }
[DataMember]
public string SomethingElse { get; set; }
[DataMember]
[JsonProperty(Order = 1)]
public float CurrentPeriodValue { get; set; }
[DataMember]
[JsonProperty(Order = 2)]
public bool HasPriorValue { get; set; }
[DataMember]
[JsonProperty(Order = 3)]
public float PriorPeriodValue { get; set; }
[DataMember]
[JsonProperty(Order = 4)]
public float ChangeOverPrior { get; set; }
[DataMember]
[JsonProperty(Order = 5)]
public float ChangeOverPriorPercent { get; set; }
导致(错误的订单):
{
"ChangeOverPrior": 8,
"ChangeOverPriorPercent": 0.25,
"CurrentPeriodValue": 40,
"HasPriorValue": true,
"PriorPeriodValue": 32,
"QueryId": "CitiesMonitored_count",
"SomethingElse": "why am I the only thing visible?"
}
关于如何验证Json.Net是否正在进行序列化的任何想法,如果是,为什么(Order =)
属性被忽略?
答案 0 :(得分:1)
正如@Jonathan Holland指出的那样,尽管有我的属性标记,但我实际上并没有使用Json.Net进行序列化。我必须实施a custom message formatter才能做到这一点。幸运的是,我想要做的事情可以用常规DataContractSerializer
完成,this blog post explains。
所以这将解决问题:
[DataContract]
public class ScalarResult
{
[DataMember(Order = 0)]
public string QueryId { get; set; }
[DataMember(Order = 1)]
public float CurrentPeriodValue { get; set; }
[DataMember(Order = 2)]
public bool HasPriorValue { get; set; }
[DataMember(Order = 3)]
public float PriorPeriodValue { get; set; }
[DataMember(Order = 4)]
public float ChangeOverPrior { get; set; }
[DataMember(Order = 5)]
public float ChangeOverPriorPercent { get; set; }
// rest of code here
}
现在结果符合预期:
{
"QueryId": "SystemsMonitored_count",
"CurrentPeriodValue": 60,
"HasPriorValue": true,
"PriorPeriodValue": 47,
"ChangeOverPrior": 13,
"ChangeOverPriorPercent": 0.276595742
}