【发布时间】:2021-11-12 02:45:12
【问题描述】:
如何在下面显示 JSON 响应(从 REST API 接收)并以过滤的方式将其显示在我的视图 (MVC) 中?
作为解决方案,我尝试为其创建模型,请参阅下面的结果,但问题是我无法过滤视图显示中的字段(例如,我只想显示搜索结果页面“ SiteName”并忽略其他的)。另外我认为最好有一个 Dictionary
Models.Root convertedToModel = JsonConvert.DeserializeObject<Models.Root>(jsonData);
我也尝试使用 ViewData,但不断收到 NullReferenceException。 对于以过滤方式在视图中显示 JSON 数据的更好方法有什么建议吗?
{
"Results": {
"Rows": [{
"Cells": [{
"Key": "Title",
"Value": "Some Document - 1234 ABC",
"ValueType": "Edm.String"
},
{
"Key": "Path",
"Value": "https: //contoso.sharepoint.com/sites/shipments/Shared documents/Some Document - 1234 ABC.pdf",
"ValueType": "Edm.String"
},
{
"Key": "SiteName",
"Value": "https: //contoso.sharepoint.com/sites/shipments",
"ValueType": "Edm.String"
}
]
},
{
"Cells": [{
"Key": "Title",
"Value": "Some Document - 9432 XYZ",
"ValueType": "Edm.String"
},
{
"Key": "Path",
"Value": "https: //contoso.sharepoint.com/sites/shipments/Shared documents/Some Document - 9432 XYZ.pdf",
"ValueType": "Edm.String"
},
{
"Key": "SiteName",
"Value": "https: //contoso.sharepoint.com/sites/shipments",
"ValueType": "Edm.String"
}
]
}
]
},
"TotalResult": 2
}
根据 JSON 数据创建模型:
public class Cell
{
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class Row
{
public List<Cell> Cells { get; set; }
}
public class Results
{
public List<Row> Rows { get; set; }
}
public class Root
{
public Results Results { get; set; }
public int TotalResult { get; set; }
}
查看:
<table class="table">
@foreach (var item in Model.ToList())
{
<tr>
@foreach (var cellItem in item.Cells)
{
<th>@cellItem.Key</th>
}
</tr>
<tr>
@foreach (var cellItem in item.Cells)
{
<td>@cellItem.Value</td>
}
</tr>
}
</table>
【问题讨论】:
-
您提供的 json 似乎不是有效的 json,根据:jsonformatter.curiousconcept.com
标签: c# json asp.net-mvc asp.net-core json.net