Blazor C#中如何关联两个JSON文件数据以显示国家名称
Blazor中关联两个JSON数据显示国家名称解决方案
步骤1:修正JSON文件格式
你的第一个JSON文件缺少数组包裹,反序列化会失败,需修改为标准数组格式:
[{"CountryIso2":"AF","CountryName":"Afghanistan"},{"CountryIso2":"AN","CountryName":"Netherlands"}]
步骤2:反序列化并构建国家映射字典
使用System.Text.Json(Blazor默认推荐)读取并解析两个JSON文件,同时将国家列表转换为字典,实现快速查找:
适配Blazor Server项目
using System.Text.Json; using System.IO; // 读取国家JSON文件(路径根据项目结构调整,示例为wwwroot下的data目录) var countryJson = await File.ReadAllTextAsync("wwwroot/data/countries.json"); var countryList = JsonSerializer.Deserialize<List<Country>>(countryJson); // 构建国家代码到名称的映射字典 var countryCodeMap = countryList.ToDictionary(c => c.CountryIso2, c => c.CountryName); // 读取事件JSON文件 var eventJson = await File.ReadAllTextAsync("wwwroot/data/event.json"); var targetEvent = JsonSerializer.Deserialize<Event>(eventJson);
适配Blazor WebAssembly项目
WebAssembly无法直接读取本地文件,需通过HttpClient获取资源:
@inject HttpClient Http // ... var countryJson = await Http.GetStringAsync("data/countries.json"); var eventJson = await Http.GetStringAsync("data/event.json"); // 后续反序列化和字典构建逻辑同上
步骤3:在Blazor页面关联并显示数据
在Razor页面中通过字典匹配国家名称,直接渲染内容:
@page "/event-details" @inject HttpClient Http @if (targetEvent != null && countryCodeMap != null) { <div class="event-card"> <h2>@targetEvent.Name</h2> <p> 时间范围: @targetEvent.Start.ToString("yyyy-MM-dd HH:mm") 至 @targetEvent.End.ToString("yyyy-MM-dd HH:mm") </p> <p>地址: @targetEvent.Address.Information, @targetEvent.Address.City</p> <p> 国家: @(countryCodeMap.TryGetValue(targetEvent.Address.CountryIso2, out var name) ? name : "未知国家") </p> <p>附加信息: @((MarkupString)targetEvent.AdditionalInformation)</p> </div> } @code { private Event targetEvent; private Dictionary<string, string> countryCodeMap; protected override async Task OnInitializedAsync() { // 初始化数据 var countryJson = await Http.GetStringAsync("data/countries.json"); var countryList = JsonSerializer.Deserialize<List<Country>>(countryJson); countryCodeMap = countryList.ToDictionary(c => c.CountryIso2, c => c.CountryName); var eventJson = await Http.GetStringAsync("data/event.json"); targetEvent = JsonSerializer.Deserialize<Event>(eventJson); } // 复用你的模型类,建议将Addressar改为Address以符合命名规范 public class Event { public string Name { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public string AdditionalInformation { get; set; } public Address Address { get; set; } } public class Address { public string Information { get; set; } public string City { get; set; } public string CountryIso2 { get; set; } } public class Country { public string CountryIso2 { get; set; } public string CountryName { get; set; } } }
额外优化建议
- 将国家映射字典封装为单例服务,注入到组件中,避免重复读取解析JSON。
- 添加try-catch块处理反序列化异常,提升稳定性。
- 若国家数据固定,可直接硬编码字典,减少文件IO开销。
内容的提问来源于stack exchange,提问作者Gamer X.
相关产品推荐
相关产品推荐

