C# Xamarin如何从List选取同类型值并转换指定JSON为List?
解决C# Xamarin中特定JSON转List的问题
嘿,我来帮你搞定这个JSON转List的问题!你的JSON结构有点特殊——Products里的每个元素都是只装了一个price对象的子数组,所以不能直接反序列化到List<price>,得先处理这个嵌套结构,具体步骤如下:
1. 先定义根对象类
因为你的JSON外层有一个Products属性,而这个属性的值是嵌套的二维列表,所以我们需要先定义一个对应外层结构的根类:
public class RootObject { public List<List<price>> Products { get; set; } }
这个类的Products属性和JSON里的键名完全对应,用来承接反序列化后的外层数据。
2. 反序列化并展开嵌套列表
接下来我们用常用的JSON库来处理反序列化,这里推荐Newtonsoft.Json(Json.NET),Xamarin项目里可以直接通过NuGet安装它。如果偏好.NET Core自带的System.Text.Json也可以,两种方式都给你列出来:
方式一:用Newtonsoft.Json
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; // 假设jsonString是你拿到的目标JSON字符串 var rootObj = JsonConvert.DeserializeObject<RootObject>(jsonString); // 用SelectMany把二维列表平铺成一维的List<price> List<price> priceList = rootObj.Products.SelectMany(subList => subList).ToList();
方式二:用System.Text.Json
using System.Text.Json; using System.Collections.Generic; using System.Linq; // 忽略大小写匹配(如果JSON和类属性大小写不一致时很有用) var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var rootObj = JsonSerializer.Deserialize<RootObject>(jsonString, options); List<price> priceList = rootObj.Products.SelectMany(subList => subList).ToList();
这里的SelectMany是关键——它会把嵌套的每个子列表里的元素全部提取出来,拼成一个单一的列表,正好满足你需要的List<price>结构。
额外注意点
- 如果你的
price类属性名和JSON键名不一致(比如类里用小写name,JSON里是大写NAME),可以用特性来映射:Newtonsoft.Json用[JsonProperty("NAME")],System.Text.Json用[JsonPropertyName("NAME")]。 - 确保你已经在Xamarin项目里安装了对应的JSON库:Newtonsoft.Json直接在NuGet搜索安装即可,System.Text.Json是.NET Core/Xamarin.Forms默认包含的,不需要额外安装。
内容的提问来源于stack exchange,提问作者user9198450
相关产品推荐
相关产品推荐

