如何在C#中将飞利浦Hue桥返回的非数组JSON反序列化为List?
解决飞利浦Hue桥灯光列表JSON反序列化问题
飞利浦Hue API返回的灯光数据是以灯光ID为键的JSON对象,而非数组结构,直接反序列化为List<T>会失败。正确的做法是先用字典类型接收,再提取值转为集合。下面是两种C#常用序列化库的实现方案:
1. 使用Newtonsoft.Json(Json.NET)
第一步:定义对应实体类
根据JSON结构创建匹配的实体类:
public class LightState { public bool on { get; set; } public int bri { get; set; } public int hue { get; set; } public int sat { get; set; } public string effect { get; set; } public double[] xy { get; set; } public int ct { get; set; } public string alert { get; set; } public string colormode { get; set; } public string mode { get; set; } public bool reachable { get; set; } } public class Light { public LightState state { get; set; } // API返回其他字段时,可在此添加对应属性 }
第二步:反序列化并转为List
用Dictionary<string, Light>接收JSON,再提取Values转为集合:
string json = "你的API返回的JSON字符串"; var lightDictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Light>>(json); List<Light> lights = lightDictionary.Values.ToList();
2. 使用System.Text.Json(.NET Core/.NET 5+内置)
第一步:定义实体类
实体类和上面完全一致:
public class LightState { public bool on { get; set; } public int bri { get; set; } public int hue { get; set; } public int sat { get; set; } public string effect { get; set; } public double[] xy { get; set; } public int ct { get; set; } public string alert { get; set; } public string colormode { get; set; } public string mode { get; set; } public bool reachable { get; set; } } public class Light { public LightState state { get; set; } }
第二步:反序列化并转为List
使用内置序列化器处理:
string json = "你的API返回的JSON字符串"; var lightDictionary = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, Light>>(json); List<Light> lights = lightDictionary?.Values.ToList() ?? new List<Light>();
补充说明
你之前尝试加括号转数组的方式失败,是因为原始JSON本质是键值对对象,强行修改结构会丢失灯光ID的关联信息,且不符合API固定返回格式。直接用字典接收是最稳妥的方式,如果需要保留灯光ID,直接使用Dictionary<string, Light>即可,键就是对应灯光的ID。
内容的提问来源于stack exchange,提问作者Marius Christiansen
相关产品推荐
相关产品推荐

