gpt4 book ai didi

c# - 读取 JSON 对象

转载 作者:行者123 更新时间:2023-12-02 18:16:17 27 4
gpt4 key购买 nike

我正在尝试使用 JavaScriptSerializer 读取 JSON 对象。目前我无法使用我的代码读取 JSON 对象。

下面是我的 JSON 对象。

{"data":[{"id":17,"name":"RedBug Project","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0}},{"id":14,"name":"RedRock","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":0},"children":[{"id":16,"name":"WEB","can_modify":true,"description":"","start_date":"1899-01-01T00:00:00Z","due_date":"1899-01-01T00:00:00Z","is_active":true,"parent":{"id":14}}]}]}

读取JSON的方法

public Dictionary<string, string> ReadJSONProject(string jsObject)
{

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

Dictionary<string, string> dic = new Dictionary<string, string>();

foreach (var item in jsonObject)
{
var a = item;
dic.Add(item["id"], item["name"]);

}

return dic;
}

我需要将以下值读取到字典中

"id":17,"name":"RedBug Project"

"id":14,"name":"RedRock"

最佳答案

namespace WebApplication2
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string s = @"{""data"":[{""id"":17,""name"":""RedBug Project"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0}},{""id"":14,""name"":""RedRock"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":0},""children"":[{""id"":16,""name"":""WEB"",""can_modify"":true,""description"":"""",""start_date"":""1899-01-01T00:00:00Z"",""due_date"":""1899-01-01T00:00:00Z"",""is_active"":true,""parent"":{""id"":14}}]}]}";
ReadJSONProject(s);
}

protected Dictionary<string, string> ReadJSONProject(string jsObject)
{

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

Dictionary<string, string> dic = new Dictionary<string, string>();

var data = jsonObject["data"];

foreach (var record in data)
{
var id = ((int)record["id"]).ToString();
var name = record["name"] as string;

dic.Add(id, name);

}

return dic;
}
}
}

关于c# - 读取 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19262666/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com