You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在C#中读取JSON文件并将内容显示到TextBox中?

问题解决方案

1. 修正JSON与C#类的结构匹配问题

你的JSON根对象是包含thruster数组的容器,而非直接的数组,同时JSON里的id是数字类型,需调整C#类结构:

// 新增容器类匹配JSON外层结构
public class ThrusterContainer
{
    public List<thruster> thruster { get; set; }
}

public class thruster
{
    public int id { get; set; } // 将string改为int,匹配JSON中的数字类型
    public string type { get; set; }
    public string placement { get; set; }
}

2. 修复反序列化逻辑

原代码直接反序列化成List<thruster>会失败,需改为反序列化成容器类:

string text = File.ReadAllText(@"./thrusters.json");
ThrusterContainer container = JsonConvert.DeserializeObject<ThrusterContainer>(text);

3. 正确填充TextBox内容

原循环每次覆盖textBox1.Text,导致仅显示最后一条数据,需拼接所有内容:

textBox1.Text = ""; // 先清空TextBox
foreach (var item in container.thruster)
{
    // 自定义显示格式,每行展示一个推进器的完整信息
    string placement = item.placement ?? "未指定";
    textBox1.Text += $"ID: {item.id} | 类型: {item.type} | 安装位置: {placement}\r\n";
}

4. 移除无限递归

原方法末尾的return Getthruster();会导致无限递归,直接调整方法为无返回值类型:

private void LoadThrusters()
{
    try
    {
        string text = File.ReadAllText(@"./thrusters.json");
        ThrusterContainer container = JsonConvert.DeserializeObject<ThrusterContainer>(text);

        textBox1.Text = "";
        foreach (var item in container.thruster)
        {
            string placement = item.placement ?? "未指定";
            textBox1.Text += $"推进器 {item.id}: 类型={item.type}, 安装位置={placement}\r\n";
        }
    }
    catch (Exception ex)
    {
        textBox1.Text = $"加载失败: {ex.Message}";
    }
}

完整修正代码

public class ThrusterContainer
{
    public List<thruster> thruster { get; set; }
}

public class thruster
{
    public int id { get; set; }
    public string type { get; set; }
    public string placement { get; set; }
}

private void LoadThrusters()
{
    try
    {
        string text = File.ReadAllText(@"./thrusters.json");
        ThrusterContainer container = JsonConvert.DeserializeObject<ThrusterContainer>(text);

        textBox1.Text = "";
        foreach (var item in container.thruster)
        {
            string placement = item.placement ?? "未指定";
            textBox1.Text += $"推进器 {item.id}: 类型={item.type}, 安装位置={placement}\r\n";
        }
    }
    catch (Exception ex)
    {
        textBox1.Text = $"加载失败: {ex.Message}";
    }
}

内容的提问来源于stack exchange,提问作者Tangen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 00:31:14