转换JSON字符串到C#对象 [英] Convert JSON String To C# Object
问题描述
尝试将JSON字符串转换成C#的对象。用一个非常简单的测试用例:
Trying to convert a JSON string into an object in C#. Using a really simple test case:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
object routes_list = json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
问题在于routes_list从未获取设置;它是一个未定义的对象。任何想法?
The problem is that routes_list never gets set; it's an undefined object. Any ideas?
推荐答案
它看起来像你试图反序列化到原始对象。您可以创建重新presents,你转换为对象的类。这将是在你处理较大的物体或JSON字符串的情况下非常有用。
It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.
例如:
class Test {
String test;
String getTest() { return test; }
void setTest(String test) { this.test = test; }
}
那么你的反序列化code将是:
Then your deserialization code would be:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");
更多信息可以在本教程中找到:
<一href=\"http://www.$c$cproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx\">http://www.$c$cproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
这篇关于转换JSON字符串到C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!