使用 Json.NET 将任何类型的对象转换为 JObject
本文介绍了使用 Json.NET 将任何类型的对象转换为 JObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用 WebAPI 将其返回给客户端之前,我经常需要使用附加信息扩展我的域模型.为了避免创建 ViewModel,我想我可以返回带有附加属性的 JObject.但是,我无法找到直接方法将任何类型的对象转换为 JObject,只需调用 Newtonsoft JSON 库即可.我想出了这样的事情:
I often need to extend my Domain model with additional info before returning it to the client with WebAPI. To avoid creation of ViewModel I thought I could return JObject with additional properties. I could not however find direct way to convert object of any type to JObject with single call to Newtonsoft JSON library. I came up with something like this:
- 第一个 SerializeObject
- 然后解析
- 并扩展 JObject
例如:
我这个方法正确吗?
推荐答案
JObject 实现了 IDictionary,所以你可以这样使用它.例如,
JObject implements IDictionary, so you can use it that way. For ex,
所以最终的 json 将是
So the final json will be
你也可以使用动态
关键字
这篇关于使用 Json.NET 将任何类型的对象转换为 JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!