将 JSON 字符串反序列化为 c# 对象 [英] Deserialize JSON string to c# object
问题描述
我的应用程序在用 C# 编码的 Asp.Net MVC3 中.这就是我的要求.我想要一个如下格式的对象.这个对象应该在我反序列化Json字符串时实现.
My Application is in Asp.Net MVC3 coded in C#. This is what my requirement is. I want an object which is in the following format.This object should be achieved when I deserialize the Json string.
var obj1 = new { arg1=1,arg2=2 };
使用以下代码后:
string str = "{"Arg1":"Arg1Value","Arg2":"Arg2Value"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize<object>(str);
我得到的对象,即 obje 不作为 obj1
The object what i get i.e obje does not acts as obj1
在这里,在这个例子中,我的 JSON 字符串是静态的,但实际上 JSON 字符串将是动态生成的运行时,所以我将无法一直获取 Arg1 和 Arg2.
Here, in this example my JSON string is static, but actually JSON string is going to be dynamically generated runtime, so i won't be able get Arg1 and Arg2 all the time.
推荐答案
我认为 JavaScriptSerializer 不会创建动态对象.
I think the JavaScriptSerializer does not create a dynamic object.
所以你应该先定义类:
class MyObj {
public int arg1 {get;set;}
public int arg2 {get;set;}
}
并反序列化它而不是object
:
serializer.Deserialize<MyObj>(str);
不是 testet,请尝试.
Not testet, please try.
这篇关于将 JSON 字符串反序列化为 c# 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!