[英]WriteJson override with JSON.NET library
I made a simple JsonConverter
because I have a page that posts a JSON array which can be of a generic type. 我做了一个简单的JsonConverter
因为我有一个页面发布了可以是通用类型的JSON数组。
Posting JSON data and converting that to a typed object works fine using the overriden ReadJson
method in my custom JsonConverter
class. 使用自定义JsonConverter
类中的重写ReadJson
方法,可以将JSON数据发布并将其转换为类型对象。
I also need to read from the database again and I do that like this: 我还需要再次从数据库中读取数据,并且这样做:
public Element GetElementById(ObjectId id)
{
return Db.GetCollection<Element>("Elements").Find(x => x.Id == id).FirstOrDefaultAsync().Result;
}
The above method is called by a WebApi
method: 上面的方法由WebApi
方法调用:
[HttpGet]
public Element GetElement()
{
var element = _elementService.GetElementById(new ObjectId("123e4567b4775f1c48bdabcd"));
return element;
}
From there it returns the right object from the database. 从那里,它从数据库返回正确的对象。 But after the return element
then the WriteJson
json override method is called in my custom JsonConverter
class. 但是在return element
之后,然后在我的自定义JsonConverter
类中调用WriteJson
json重写方法。 That method looks like this: 该方法如下所示:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
I don't need to do anything special in the WriteJson
method. 我不需要在WriteJson
方法中做任何特别的WriteJson
。 Because the object that is returned from the database is good. 因为从数据库返回的对象是好的。 I'd just like to let the WebApi
convert that object to JSON and all should be good. 我只想让WebApi
将对象转换为JSON,一切都应该很好。
Then how do I implement the WriteJson
method when I don't need to do anything special in it? 那么,当我不需要做任何特别的事情时,该如何实现WriteJson
方法呢?
覆盖CanWrite
并返回false:
public override bool CanWrite { get { return false; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.