Xamarin.Forms中创建C#类解析嵌套JSON获取actual字段
解决方案
针对你提供的嵌套JSON结构,你需要创建三层C#类来对应JSON的层级关系,之后就能轻松解析并获取intensity中的actual字段。
1. 定义对应JSON结构的C#类
根据JSON的嵌套层级,分别创建以下类:
Intensity类(对应嵌套的intensity对象)
public class Intensity { public int Forecast { get; set; } // 你需要获取的actual字段 public int Actual { get; set; } public string Index { get; set; } }
DataItem类(对应data数组中的单个元素)
public class DataItem { public string From { get; set; } public string To { get; set; } // 嵌套的Intensity对象 public Intensity Intensity { get; set; } }
ApiResponse类(对应整个API响应的根结构)
public class ApiResponse { // 对应JSON里的data数组 public List<DataItem> Data { get; set; } }
2. 解析JSON并获取actual字段
Xamarin.Forms中常用System.Text.Json(.NET内置)或Newtonsoft.Json(第三方NuGet包)来反序列化JSON,以下是两种方式的示例:
方式一:使用System.Text.Json(无需额外安装包)
// 假设你已经通过API请求拿到了完整的JSON响应字符串responseString var apiResponse = System.Text.Json.JsonSerializer.Deserialize<ApiResponse>(responseString); // 安全获取第一个数据项的actual值 if (apiResponse?.Data != null && apiResponse.Data.Count > 0) { int actualValue = apiResponse.Data[0].Intensity.Actual; // 这里可以使用actualValue做后续业务处理 }
方式二:使用Newtonsoft.Json(需先安装NuGet包Newtonsoft.Json)
var apiResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(responseString); if (apiResponse?.Data != null && apiResponse.Data.Any()) { int actualValue = apiResponse.Data[0].Intensity.Actual; }
注意事项
如果JSON字段名和C#属性名大小写不匹配(比如JSON是from,C#是From),默认情况下两种序列化库都会自动处理驼峰与帕斯卡命名的映射。如果需要更精确的控制,可以给属性添加特性:
// System.Text.Json的特性 [System.Text.Json.Serialization.JsonPropertyName("from")] public string From { get; set; } // Newtonsoft.Json的特性 [Newtonsoft.Json.JsonProperty("from")] public string From { get; set; }
内容的提问来源于stack exchange,提问作者Ethan Lewis
相关产品推荐
相关产品推荐

