如何反序列化JObject到.NET对象 [英] How to deserialize an JObject to .NET object
问题描述
我愉快地使用 Newtonsoft JSON库。
例如,我将创建一个 JObject
从.NET对象,在这种情况下异常的情况下(可能是也可能不是一个子类)
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);
但我在找的是:
but what I am looking for is:
// 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.
推荐答案
根据这个<一个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屋!