使用NewtonSoft将JSON对象反序列化为.Net对象 [英] Deserialize JSON Object to .Net object with NewtonSoft

查看:77
本文介绍了使用NewtonSoft将JSON对象反序列化为.Net对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON对象,我想在不强制转换的情况下将其反序列化为.Net类型.

I got a json Object that i want to deserialize to its .Net type without casting it.

我认为我在文档中某处读到可以将属性传递到json中,以告知反序列化器可以尝试转换的.Net对象类型.

I think i read somewhere in the doc that you can pass an attribute into the json to tells to the deserializer the .Net object type that it can try to cast.

我在哪里找不到我的书.

I can't find the where i read this.

我想避免使用

var myNewObject = JsonConvert.DeserializeObject<MyClass>(json);

要得到这样的东西

MyClass myNewObject = JsonConvert.DeserializeObject(json);

我从HttpRequest中获取了json对象,并希望从此嵌套对象中实例化适当的类. 当前,将反序列化为已知项效果很好,但需要更灵活的方法,而无需通过解析方法来管理所有已知对象.

I got my json object from an HttpRequest and want to instantiate the appropriate class from this nested object. Currently deserialization into an known item work good but need something more flexible without the need to manage all known Object from a parsing method.

推荐答案

您可以像这样将对象类型保存在json字符串中.

You can save the object type in your json string like this.

您需要交接转换器的设置

The settings you have to hand over the converter

public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
   TypeNameHandling = TypeNameHandling.Objects
};

如何使用给定的设置进行序列化:

How to serialize with the given settings:

var json = JsonConvert.SerializeObject(data, Settings);

这是您的json字符串的样子:

This is what your json string looks like:

{
   "$type":"YourNamespaceOfTheClass",
   "YourPropertyInTheClass":valueOfProperty
}

如何使用给定的设置反序列化:

How to deserialize with the given settings:

var object = JsonConvert.DeserializeObject(json, Settings);

现在,您的json字符串不仅包含序列化的对象,还包含序列化对象的类型.因此,在反序列化json字符串时,您不必担心正确的类型.

Now your json string contains not only the serialized object, but also the type of your serialized object. So you don't have to worry about the right type when deserializing your json string.

这篇关于使用NewtonSoft将JSON对象反序列化为.Net对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆