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

.NET Core MVC中如何解析JSON数据并在视图中过滤展示

方案1(推荐):扩展模型实现字典转换,无需修改原有反序列化逻辑

你不需要调整现有的JSON反序列化代码,只需要给Row类新增一个只读的计算属性,自动把Cells集合转成字典即可:

public class Row
{
    public List<Cell> Cells { get; set; }
    // 新增自动转换的字典属性,反序列化时不会被处理,不影响原有逻辑
    public Dictionary<string, string> CellsMap => 
        Cells?.ToDictionary(c => c.Key, c => c.Value) ?? new Dictionary<string, string>();
}

控制器传递强类型模型

直接把反序列化后的行集合传给视图,避免ViewData的空引用问题:

public IActionResult SearchResult()
{
    // 你的原有API请求、JSON获取逻辑
    string jsonData = "REST API返回的JSON字符串";
    Root convertedToModel = JsonConvert.DeserializeObject<Root>(jsonData);
    // 强类型传值给视图,避免空引用
    return View(convertedToModel.Results.Rows);
}

视图层过滤展示指定字段

首先在视图顶部声明绑定的模型类型:

@model IEnumerable<你的项目命名空间.Models.Row>

然后修改表格代码,只取你需要的SiteName字段:

<table class="table">
    <thead>
        <tr>
            <th>站点名称</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var row in Model)
        {
            <tr>
                <!-- 用GetValueOrDefault避免找不到Key时报空 -->
                <td>@row.CellsMap.GetValueOrDefault("SiteName", "无匹配数据")</td>
            </tr>
        }
    </tbody>
</table>

后续如果需要展示其他字段,比如Title,直接新增对应列即可,灵活性很高。


方案2:不修改模型,直接在视图过滤

如果你不想调整现有模型代码,直接修改视图的循环逻辑,过滤出指定Key的单元格即可:

<table class="table">
    <thead>
        <tr>
            <th>站点名称</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var row in Model)
        {
            <tr>
                <td>@row.Cells.FirstOrDefault(c => c.Key == "SiteName")?.Value ?? "无匹配数据"</td>
            </tr>
        }
    </tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:42:02