选择筛选JArray

时间:2020-08-24 06:46:50

标签: c#

我有一个JArray如下:

boost::in_pace

如何按 [ { "id": 5447, "attributes": { "alarm": "Mode1" }, "deviceId": 28 }, { "id": 5448, "attributes": { "alarm": "Mode1" }, "deviceId": 28 }, { "id": 5449, "attributes": { "alarm": "Mode2" }, "deviceId": 28 } ] 进行过滤?

我尝试过:

["attributes"]["alarm"] == "Mode1"

它返回null吗?

1 个答案:

答案 0 :(得分:1)

您可以反序列化

给予

public class Attributes    {
   public string alarm { get; set; } 
}

public class Model    {
   public int id { get; set; } 
   public Attributes attributes { get; set; } 
   public int deviceId { get; set; } 
}

用法

var model = JsonConvert
    .DeserializeObject<List<Model>>(input)
    .FirstOrDefault(x => x.attributes.alarm == "Mode1");

var result = JArray
    .Parse(input)
    .FirstOrDefault(x => (string) x["attributes"]["alarm"] == "Mode1")
    .ToObject<Model>();

如果要显示匹配项列表,请使用Where而不是FirstOrDefault