参见英文答案 >
Newtonsoft JSON.net deserialization error where fields in JSON change order1个
我的web api中有以下方法
public void Put(string id,[FromBody]IContent value) {
//Do stuff
}
我正在使用骨干js使用fiddler将以下JSON发送到服务器,值为null:
{
"id": "articles/1","heading": "Bar","$type": "BrickPile.Samples.Models.Article,BrickPile.Samples"
}
但是如果我在JSON对象中首先添加$type属性,反序列化工作正常,请参阅:
{
"$type": "BrickPile.Samples.Models.Article,BrickPile.Samples","id": "articles/1","heading": "Bar"
}
是否可以配置newtonsoft以检查对象中的$type属性而不是第一个属性,还是可以配置主干,以便它始终首先在JSON对象中添加$type属性?
解决方法
这将在骨干网中起作用,但我不知道每个浏览器的行为是否相同.基本上,并不能保证每个浏览器都会按照添加的顺序保留项目.
MyModel = Backbone.Model.extend({
// ...
toJSON: function(){
// build the "$type" as the first parameter
var json = {"$type": "BrickPile.Samples.Models.Article,BrickPile.Samples"};
// get the rest of the data
_.extend(json,Backbone.Model.prototype.toJSON.call(this));
// send it back,and hope it's in the right order
return json;
}
});
不过,你最好让NewtonSoft的JSON解串器工作,而不需要它在特定的位置.希望这是可能的.
