如何反序列化JObject到.NET对象对象、序列化、JObject、NET

2023-09-02 21:56:41 作者:眼泪被雨滴冷却

我愉快地使用 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.

推荐答案

根据这个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转换到一个类型

 
精彩推荐
图片推荐