反序列化JSON字符串到C#对象 [英] Deserialize JSON string to c# object
问题描述
我的应用程序是在C#Asp.Net MVC3 codeD。
这是我的要求是什么。我想要一个对象,它是在以下format.This对象时,我反序列化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 };
使用低于code之后:
After using the below code:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize<object>(str);
对象是我所得到即 OBJE 不作为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.
所以,你应该首先定义类:
So you should define the class first:
class MyObj {
public int arg1 {get;set;}
public int arg2 {get;set;}
}
和反序列化,而不是对象
:
serializer.Deserialize<MyObj>(str);
不testet,请尝试。
Not testet, please try.
这篇关于反序列化JSON字符串到C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!