加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

序列化 – Newtonsoft中的TypeNameHandling需要$type作为第一个

发布时间:2020-12-15 20:56:17 所属栏目:asp.Net 来源:网络整理
导读:参见英文答案 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发送到服务器,值为nul
参见英文答案 > 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解串器工作,而不需要它在特定的位置.希望这是可能的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读