在Newtonsoft TypeNameHandling需要$类型为第一个属性? [英] TypeNameHandling in Newtonsoft requires $type to be the first property?

查看:206
本文介绍了在Newtonsoft TypeNameHandling需要$类型为第一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的方法在我的web API

I have the following method in my web api

public void Put(string id, [FromBody]IContent value) {
    //Do stuff
}

我用JS骨干发送以下JSON使用小提琴手服务器值为null:

I'm using backbone js to send the following JSON to the server using fiddler the value is null:

{
    "id": "articles/1",
    "heading": "Bar",
    "$type": "BrickPile.Samples.Models.Article, BrickPile.Samples"
}

但如果我在JSON对象反序列化工作正常先添加$ type属性,见:

but if I add the $type property first in the JSON object the deserialization works fine, see:

{
 "$type": "BrickPile.Samples.Models.Article, BrickPile.Samples",
  "id": "articles/1",
  "heading": "Bar" 
}

是有可能配置newtonsoft到对象,而不是第一个属性的任何地方检查$ type属性或我可以配置骨干所以它总是添加 $类型财产首先在JSON对象?

is it possible to configure newtonsoft to check for the $type property anywhere in the object instead of the first property or can I configure backbone so it always adds the $type property first in the JSON object?

推荐答案

这将在骨干工作,但我不知道是否所有的浏览器将具有相同的行为。有没有保证,基本上,每一个浏览器将保持它们添加顺序的项目。

This will work in backbone, but I don't know if every browser will behave the same. There's no guarantee, basically, that every browser will keep the items in the order which they are added.


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解串器,而不需要在一个特定的位置上工作,虽然效果更好。希望这将是可能的。

You're better of getting NewtonSoft's JSON deserializer to work without needing it in a specific position, though. Hopefully that will be possible.

这篇关于在Newtonsoft TypeNameHandling需要$类型为第一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆