【发布时间】:2021-09-15 15:29:07
【问题描述】:
我需要帮助迭代 C# 中的 JSON 响应。我想输出 Item.Name。 我是否需要为班级中 json 正文中的每个标记添加一个属性?
我下面的内容不起作用。感谢您的帮助。
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
namespace RuneScape_GE_API
{
class Program
{
static void Main(string[] args)
{
var url = "https://secure.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=21787";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var jsonResult = response.Content.ReadAsStringAsync().Result;
item citem = JsonConvert.DeserializeObject<item>(jsonResult);
}
}
}
public class item
{
public string name { get; set; }
}
}
示例 JSON: { “物品”:{ "图标":"https://secure.runescape.com/m=itemdb_rs/1624875191508_obj_sprite.gif?id=21787", "icon_large":"https://secure.runescape.com/m=itemdb_rs/1624875191508_obj_big.gif?id=21787", “身份证”:21787, “类型”:“其他”, "typeIcon":"https://www.runescape.com/img/categories/Miscellaneous", "name":"坚定的靴子", "description":"一双威风凛凛的靴子。", “当前的”:{ “趋势”:“中性”, “价格”:“4.8m” }, “今天”:{ “趋势”:“中性”, “价格”:0 }, “成员”:“真实”, “第 30 天”:{ “趋势”:“负面”, “变化”:“-6.0%” }, “第 90 天”:{ “趋势”:“负面”, “变化”:“-10.0%” }, “第 180 天”:{ “趋势”:“负面”, “变化”:“-19.0%” } } }
【问题讨论】:
-
能否包含 POCO 类和 json 样本?您没有尝试迭代结果。你的意思是反序列化失败了吗?
-
我想通了。在类属性中添加 JsonProperty 并使用 for 循环转换为字典。