如何反序列化JObject到.NET对象 [英] How to deserialize an JObject to .NET object
问题描述
我很高兴地使用 Newtonsoft JSON库。
例如,我将从.NET对象创建一个 JObject
,在这种情况下是Exception的一个实例(可能是或可能不是一个子类)
I happily use the Newtonsoft JSON library.
For example I would create a JObject
from an .NET object, in this case a instance of Exception (might or might not be a subclass)
if (result is Exception)
var jobjectInstance = JObject.FromObject(result);
现在我知道库可以将JSON文本(即字符串)反序列化为对象
now I know the library can deserialize JSON text (i.e. a string) to an object
// only works for text (string)
Exception exception = JsonConvert.DeserializeObject<Exception>(jsontext);
但我正在寻找的是:
// now i do already have an JObject instance
Exception exception = jobjectInstance.????
很明显,我可以从 JObject
返回JSON文本,然后使用反序列化功能,但这似乎是向后退的。
Well it is clear that I can go from on JObject
back to JSON text and then use the deserialize functionality, but that seems backwards to me.
推荐答案
根据这个< a href =http://www.west-wind.com/weblog/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing> post ,现在好多了:
According to this post, it's much better now:
// pick out one album
JObject jalbum = albums[0] as JObject;
// Copy to a static Album instance
Album album = jalbum.ToObject<Album>();
文档: 将JSON转换为类型
这篇关于如何反序列化JObject到.NET对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!