Newtonsoft中的TypeNameHandling需要$ type作为第一个属性吗?

Mar*_*cus 7 serialization json.net backbone.js asp.net-mvc-4 asp.net-web-api

我的web api中有以下方法

public void Put(string id, [FromBody]IContent value) {
    //Do stuff
}
Run Code Online (Sandbox Code Playgroud)

我正在使用骨干js使用fiddler将以下JSON发送到服务器,值为null:

{
    "id": "articles/1",
    "heading": "Bar",
    "$type": "BrickPile.Samples.Models.Article, BrickPile.Samples"
}
Run Code Online (Sandbox Code Playgroud)

但是如果我在JSON对象中首先添加$ type属性,反序列化工作正常,请参阅:

{
 "$type": "BrickPile.Samples.Models.Article, BrickPile.Samples",
  "id": "articles/1",
  "heading": "Bar" 
}
Run Code Online (Sandbox Code Playgroud)

是否可以配置newtonsoft以检查对象中的$ type属性而不是第一个属性,还是可以配置主干,以便它始终$type首先在JSON对象中添加属性?

Der*_*ley 1

这将在主干中工作,但我不知道是否每个浏览器都会表现相同。基本上,不能保证每个浏览器都会按照添加的顺序保留项目。


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;
  }


});
Run Code Online (Sandbox Code Playgroud)

不过,您最好让 NewtonSoft 的 JSON 反序列化器工作,而不需要将其放在特定位置。希望这是可能的。