将 JSON 字符串反序列化为 c# 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10350982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:30:42  来源:igfitidea点击:

Deserialize JSON string to c# object

c#jsonasp.net-mvc-3c#-4.0

提问by Shahbaz Chishty

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.

我的应用程序在用 C# 编码的 Asp.Net MVC3 中。这就是我的要求。我想要一个具有以下格式的对象。当我反序列化 Json 字符串时应该实现这个对象。

var obj1 = new { arg1=1,arg2=2 };

enter image description here

在此处输入图片说明

After using the below code:

使用以下代码后:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize<object>(str);

The object what i get i.e objedoes not acts as obj1

我得到的对象即obje不作为 obj1

enter image description here

在此处输入图片说明

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.

在这里,在此示例中,我的 JSON 字符串是静态的,但实际上 JSON 字符串将是动态生成的运行时,因此我将无法始终获取 Arg1 和 Arg2。

采纳答案by Marc

I think the JavaScriptSerializer does not create a dynamic object.

我认为 JavaScriptSerializer 不会创建动态对象。

So you should define the class first:

所以你应该先定义类:

class MyObj {
    public int arg1 {get;set;}
    public int arg2 {get;set;}
}

And deserialize that instead of object:

并反序列化它而不是object

serializer.Deserialize<MyObj>(str);

Not testet, please try.

不是testet,请尝试。

回答by Eric

I believe you are looking for this:

我相信你正在寻找这个:

string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

回答by Veni Souto

Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:

同样的问题发生在我身上。因此,如果服务将响应作为 JSON 字符串返回,您必须先反序列化该字符串,然后您才能正确地反序列化对象类型:

string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
        {
            json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());

        }
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
         {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(@json);
            memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8,          XmlDictionaryReaderQuotas.Max, null))
            {
                var serializer = new DataContractJsonSerializer(typeof(MyType));
                myType = (MyType)serializer.ReadObject(jsonReader);

            }
        }

4 Sure it will work.... ;)

4 当然它会起作用....;)

回答by A. Acosta

This may be useful:

这可能很有用:

var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);

Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use

其中“json”是包含 JSON 值的字符串。然后从您可以使用的 jsonObject 中检索值

myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);

Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).

将 MyPropertyType 更改为正确的类型(ToInt32、ToString、ToBoolean 等)。

回答by Ridwan Galib

Use this code:

使用此代码:

var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);

回答by sachin

solution :

解决方案 :

 public Response Get(string jsonData) {
     var json = JsonConvert.DeserializeObject<modelname>(jsonData);
     var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
     return data;
 }

model:

模型:

 public class modelname {
     public long parameter{ get; set; }
     public int parameter{ get; set; }
     public int parameter{ get; set; }
     public string parameter{ get; set; }
 }