Home > Enterprise >  How to filter JArray?
How to filter JArray?

Time:05-22

I have a JArray as below, how to filter it by "to" and "from"?, I have tried the following:

JArray ja_test = (JArray)(ja_chat
    .Children<JArray>()
    .Where(o => (int)o["data"]["from"] == 49 && (int)o["data"]["to"] == 10));

but it throws:

Unable to cast object of type WhereEnumerableIterator'1[Newtonsoft.Json.Linq.JArray] to type Newtonsoft.Json.Linq.JArray

how to achieve this?

[
  {
    "data": {
      "to": 49,
      "from": 50,
      "text": "Hi Dev",
      "files": [],
      "msg_id": "__chat__",
      "datetime": "2022-05-22 12:23:14"
    }
  },
  {
    "data": {
      "to": 49,
      "from": 10,
      "text": "Hello Dev",
      "files": [],
      "msg_id": "__chat__",
      "datetime": "2022-05-22 12:23:14"
    }
  }
]

CodePudding user response:

You have to parse json at first. Try this, it will return an array of JObject

var JArray jaChat = JArray.Parse(json);

JObject[] jaTest = jaChat.Where( o =>
        (int)o["data"]["from"] == 10 && (int)o["data"]["to"] == 49)
        .Select(o=> (JObject)o).ToArray();

or if you want a JArray, you have to convert JObject[] to JArray

    JArray jaTest1 = JArray.FromObject(jaTest);

   // or from json

    JArray jaTest = JArray.FromObject( jaChat.Where(o =>
    (int)o["data"]["from"] == 10 && (int)o["data"]["to"] == 49));
  • Related