字符串到 JSON 到二维数组 C#

String to JSON to 2D Array C#

我正在接收来自 httpWebRequest 的字符串形式的响应,其格式为 JSON。我想要的是将此字符串更改为 json 然后,有两个选项
1) 将json改为二维数组
2) 将 json 改为字典
关键是我想轻松访问变量。

这是我收到的字符串:

"[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6}... {\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]"

如您所见,我可以 table 有 n 行和 3 列(年份、姓名、Val)。

这是我用来接收响应的代码

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:5000/");

        httpWebRequest.ContentType = "application/json";

        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            //send request data in json format 
            streamWriter.Write(jsonData);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            //take data as string
            var result = streamReader.ReadToEnd();
        }
        return null;
    }

我将 return 这个 array/dictionary 而不是 null。 哪种方式更好?有人知道怎么做吗?我迷失在 C# 中。 预先感谢您的帮助!

首先,为了更轻松地使用 JSON,您可以安装 Newtonsoft.Json 软件包

Install-Package Newtonsoft.Json -Version 11.0.2

然后添加using Newtonsoft.Json;

看这个例子

public class Item
{
    public int Year { get; set; }
    public string Name { get; set; }
    public double Val { get; set; }
}

public class Program
{
    public static void Main()
    {
        string json = "[{\"Year\":2000,\"Name\":\"Ala\",\"Val\":0.5},{\"Year\":2001,\"Name\":\"Ola\",\"Val\":0.6},{\"Year\":2004,\"Name\":\"Ela\",\"Val\":0.8}]";
        List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);

        foreach(var item in items)
        {
            Console.WriteLine("Year: {0}; Name: {1}; Val: {2}", item.Year, item.Name, item.Val);
        }
    }
}

我在这里创建了一个新的 class Item 将代表您的 JSON 数组中的一个对象。然后使用 Newtonsoft.Json 将 json 字符串反序列化为项目列表。