将 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?
推荐答案
您似乎正在尝试反序列化为原始对象.您可以创建一个代表您要转换到的对象的类.这在您处理较大对象或 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; }
}
那么你的反序列化代码将是:
Then your deserialization code would be:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ "test":"some data" }");
可以在本教程中找到更多信息:http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx
这篇关于将 JSON 字符串转换为 C# 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!