本文介绍了如何在C#中将json转换为类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! RetrieveData.dll中出现'System.InvalidCastException'类型的异常,但未在用户代码中处理 附加信息:无法转换类型为'的对象System.Collections.Generic.Dictionary`2 [System.String,System.Object]'输入'RetrieveData.Models.FlightDetails'。 我是什么尝试过: 尝试将json数据转换为类对象上面的飞行细节i发布错误请帮助 - XmlDocument doc = new XmlDocument(); doc.LoadXml(dep); string jsonText = JsonConvert .SerializeXmlNode(doc); // DataTable tester =(DataTable)JsonConvert.DeserializeObject(jsonText,(typeof(DataTable))); var table = JsonConvert.DeserializeAnonymousType(jsonText,new {Makes = default(DataTable)})。Makes; JavaScriptSerializer json_serializer = new JavaS criptSerializer(); FlightDetails routes_list =(FlightDetails)json_serializer.DeserializeObject(jsonText); 解决方案 首先查看json包含的内容。这可能有所帮助: json2csharp - 从json生成c#类 [ ^ ] - 它从JSON字符串生成C#clases,然后您可以使用(或比较)应用程序中的类。 我?我使用Newtonsoft,在那里创建实例并填充它们很简单: MyClass mc = Newtonsoft.Json.JsonConvert.DeserializeObject< MyClass>(jsonString); 其中MyClass可以是任何东西:List< T>,一个单独的类实例,无论你JSON包含什么。 我有一篇文章,我根据这里的问题放在一起。它涵盖了您需要的所有内容:在C#中使用JSON& VB [ ^ ] An exception of type 'System.InvalidCastException' occurred in RetrieveData.dll but was not handled in user codeAdditional information: Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'RetrieveData.Models.FlightDetails'.What I have tried:try to Convert json Data to Class Object Flight Details above i Post the Error Please help- XmlDocument doc = new XmlDocument(); doc.LoadXml(dep); string jsonText = JsonConvert.SerializeXmlNode(doc); // DataTable tester = (DataTable)JsonConvert.DeserializeObject(jsonText, (typeof(DataTable))); var table = JsonConvert.DeserializeAnonymousType(jsonText, new { Makes = default(DataTable) }).Makes; JavaScriptSerializer json_serializer = new JavaScriptSerializer(); FlightDetails routes_list = (FlightDetails)json_serializer.DeserializeObject(jsonText); 解决方案 Start by looking at what the json contains. This may help: json2csharp - generate c# classes from json[^] - it generates C# clases from a JSON string that you can then use (or compare with) the classes in your app.Me? I use Newtonsoft, where creating the instances and filling them is simple:MyClass mc = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(jsonString);where MyClass can be anything: List<T>, a single class instance, whatever you JSON contains.I have an article that I put together based on questions here. It covers all that you need: Working with JSON in C# & VB[^] 这篇关于如何在C#中将json转换为类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-14 14:11