我已经和JSON.net合作了一段时间.我已经编写了自定义转换器和自定义合同解析器(通常来自修改SO和Newtonsoft网站上的示例),它们工作正常.
除了例子之外,我面临的挑战是,我什么时候应该使用其中一个(或两个)进行处理.根据我自己的经验,我基本上已经确定合同解决方案更简单了,所以如果我可以用他们做我需要的东西,我会这样做; 否则,我使用自定义JsonConverters.但是,我进一步知道两者有时一起使用,因此概念变得更加不透明.
问题:
使用Json.Net,我的对象中的属性需要特别小心才能序列化/反序列化它们.作为后代JsonConverter,我成功地完成了这一任务.这是执行此操作的常用方法:
public class SomeConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
...
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
...
}
public override bool CanConvert(Type objectType)
{
...
}
}
class SomeClass
{
[JsonProperty, JsonConverter(typeof(SomeConverter))]
public SomeType SomeProperty;
}
//Later on, in code somewhere
SomeClass SomeObject = new SomeClass();
string json = JsonConvert.SerializeObject(SomeObject, new SomeConverter());
Run Code Online (Sandbox Code Playgroud)
我的代码问题是我需要在每个序列化/反序列化中引入我的自定义转换器.在我的项目中,有很多情况我不能这样做.例如,我正在使用其他利用Json.Net的外部项目,他们将在我的SomeClass实例上工作.但由于我不想或无法改变他们的代码,我无法介绍我的转换器.
有没有什么方法可以static在Json.Net中使用某个成员注册我的转换器,所以无论序列化/反序列化发生在哪里,我的转换器总是存在?
我正在玩MongoDB并且有一个带有mongodb ObjectId的对象.当我使用.NET Json()方法将其序列化时,一切都很好(但日期太可怕了!)
如果我尝试使用JSON.NET序列化程序,它在尝试序列化ObjectID时会给我一个InvalidCastException
任何想法发生了什么,以及如何解决这个问题?
using MongoDB.Driver;
using MongoDB.Bson;
using Newtonsoft.Json;
//this is a route on a controller
public string NiceJsonPlease()
{
var q = new TestClass();
q.id = new ObjectId();
q.test = "just updating this";
return JsonConvert.SerializeObject(q);
}
//simple test class
class TestClass
{
public ObjectId id; //MongoDB ObjectID
public string test = "hi there";
}
Exception Details: System.InvalidCastException: Specified cast is not valid.
Run Code Online (Sandbox Code Playgroud)
如果您更改控制器方法以使用.NET附带的序列化程序,它可以正常工作(但是,这个给出了丑陋的日期,blugh)
public JsonResult NiceJsonPlease()
{
var q = new TestClass();
q.id = new ObjectId();
q.test …Run Code Online (Sandbox Code Playgroud)