json - 在视图中列出 json 类 foreach 问题
问题描述
@foreach (var clubName in item.sport_event.competitors)
{
string deneme = clubName.name;
<label>@deneme</label><br />
}
////// I used labels and br because the values are side by side.
我的问题是使用带有 Newtonsoft.Json 反序列化的 Json 数据显示团队名称。
这是我的竞争对手课程;
public class Competitor
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("country")]
public string country { get; set; }
[JsonProperty("country_code")]
public string country_code { get; set; }
[JsonProperty("abbreviation")]
public string abbreviation { get; set; }
[JsonProperty("qualifier")]
public string qualifier { get; set; }
[JsonProperty("gender")]
public string gender { get; set; }
}
这是 sport_event 类;
public class SportEvent
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("start_time")]
public DateTime start_time { get; set; }
[JsonProperty("start_time_confirmed")]
public bool start_time_confirmed { get; set; }
[JsonProperty("sport_event_context")]
public SportEventContext sport_event_context { get; set; }
[JsonProperty("coverage")]
public Coverage coverage { get; set; }
[JsonProperty("competitors")]
public IList<Competitor> competitors { get; set; }
[JsonProperty("sport_event_conditions")]
public SportEventConditions sport_event_conditions { get; set; }
[JsonProperty("venue")]
public Venue venue { get; set; }
[JsonProperty("channels")]
public IList<Channel> channels { get; set; }
}
我的问题--> 怎么才能一个个带入队名呢?还是喜欢皇家马德里-巴塞罗那?
使用我的 foreach 代码,结果是这样的;Rc Real Madrid Barcelona FC 我想要他们一一...
有我的Json例子..
"competitors": [
{
"id": "sr:competitor:35179",
"name": "Real SC Queluz",
"country": "Portugal",
"country_code": "PRT",
"abbreviation": "REQ",
"qualifier": "home",
"gender": "male"
},
{
"id": "sr:competitor:3004",
"name": "Belenenses SAD",
"country": "Portugal",
"country_code": "PRT",
"abbreviation": "SAD",
"qualifier": "away",
"gender": "male"
}
],
解决方案
假设您有一组竞争者对象。
然后代码看起来像这样:
List<Competitor> competitors = new List<Competitor>();
competitors.Add(new Competitor //code omitted...
还有其他方法可以填充竞争对手列表。现在让我们假设您在列表中有 5 个竞争者对象。接下来您要做的就是简单地遍历列表。
List 实现了 IEnumerable 接口,所以你可以只使用 foreach。
foreach (Competitor competitor in Competitors)
{
Console.WriteLine(competitor.name); //name should capitalized to Name as it's a property
}
我看到已经有一个收藏成员
[JsonProperty("competitors")]
public IList<Competitor> competitors { get; set; }
因此,您也可以使用 foreach 语句来迭代这个集合。
推荐阅读
- java - 如何在java中使用匿名类中的方法
- android - Firebase 存储:UploadTask:找不到要上传的文件
- c# - 剃刀页面上不解释自定义标签助手
- sql - 出现错误“靠近”(“:语法错误 sqlite 错误”
- javascript - React customHook 在第二次调用后返回正确的数据
- javascript - 是否在函数和主 dom 中重新声明变量?
- unity3d - 在 Unity 中交互的两个滑块
- javascript - Laravel 数组 $request->all() 为空
- git - GitLab CI - 添加标签时避免构建
- java - Java Swing - 无法使用 AWT 图形绘制圆