且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将json响应字符串反序列化为类

更新时间:2023-02-18 19:06:23

一个 JSON数组用学生数组解析它

学生[]学生= JsonConvert.DeserializeObject< Student []>(json); 
foreach(学生在学生)
{
int id = student.Id;
string name = student.Name;

}





确保学生类看起来像这样

 class学生
{
public int Id {get;组; }
public string Name {get;组; }
}


要扩展Karthik Bangalore解决方案,在C#中使用JSON& VB [ ^ ]是为Q& A这样的问题编写的CodeProject文章。它涵盖了工具,包括代码生成,帮助程序类和可以下载和运行的完整工作示例。


为了进一步扩展Karthik Bangalore的解决方案,在List&lt时你不需要使用数组; T&GT;是的,所以这就是我要做的事情:



 使用 Newtonsoft。 JSON; 
使用 System.Collections.Generic;

命名空间 WorkingWithJson
{
public class Person
{
public int Id { get ; set ; }
public string 名称{ get 跨度>; set ; }
}

public class Working_with_json
{
public static void DeserializeJSON ()
{
// 我们的json字符串
string json = @ [{Id:1 名称 : NAME1 },{ ID 为:2 名称 : NAME2 },{ ID :3 名称 : NAME3 }]跨度>;

// 反序列化为Person类型列表
List&lt ;人&GT; people = JsonConvert.DeserializeObject< List< Person>>(json);

// 然后可以检索
系统。 Console.WriteLine(

I am getting JSON response string, which is:

[{"Id":1,"Name":"name1"},{"Id":2,"Name":"name2"},{"Id":3,"Name":"name3"}]



now if I try to deserialize this string into class object and also in XmlDocument, its not working. Instead I am getting null value in both Class object and XmlDocument object.

What I have tried:

I tried the following for deserializing into a class

using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
  if (resp.StatusCode == HttpStatusCode.OK)
  {
    StreamReader rd = new StreamReader(resp.GetResponseStream());
    string str = rd.ReadToEnd(); //Here I can see the response JSON string
    Student std = JsonConvert.DeserializeObject<Student>(str);
  }
}



I tried the following for deserializing into XmlDocument

using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
  if (resp.StatusCode == HttpStatusCode.OK)
  {
    StreamReader rd = new StreamReader(resp.GetResponseStream());
    string str = rd.ReadToEnd(); //Here I can see the response JSON string
    XmlDocument xDoc = new XmlDocument();
    xDoc = JsonConvert.DeserializeXmlNode(str);
  }
}

Its a JSON array so parse it with Student Array
Student[] Students = JsonConvert.DeserializeObject<Student[]>(json);
            foreach (Student student in Students)
            {
                int id = student.Id;
                string name = student.Name;
                
            }



ensure the Student class looks like this

class Student
  {
      public int Id { get; set; }
      public string Name { get; set; }
  }


To expand on Karthik Bangalore solution, Working with JSON in C# & VB[^] is a CodeProject article written for Q&A questions like this one. It covers tools, including code generation, helper classes, and full working samples that you can download and run.


To further expand on Karthik Bangalore's solution, you dont need to use an array when List<t> is available so here's what I would do:

using Newtonsoft.Json;
using System.Collections.Generic;

namespace WorkingWithJson
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Working_with_json
    {
        public static void DeserializeJSON()
        {
            // our json string
            string json = @"[{""Id"":1,""Name"":""name1""},{""Id"":2,""Name"":""name2""},{""Id"":3,""Name"":""name3""}]";
            
            // deserializing to a list of type Person
            List<Person> people = JsonConvert.DeserializeObject<List<Person>>(json);

            // which can then be retrieved thus
            System.Console.WriteLine(