我有一个如下的JArray,如何通过“to”和“from”过滤它?,我尝试了以下方法:
JArray ja_test = (JArray)(ja_chat
.Children<JArray>()
.Where(o => (int)o["data"]["from"] == 49 && (int)o["data"]["to"] == 10));
但它抛出:
Unable to cast object of type
WhereEnumerableIterator'1[Newtonsoft.Json.Linq.JArray]
to typeNewtonsoft.Json.Linq.JArray
如何实现这一点?
[
{
"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"
}
}
]
最佳答案
首先你必须解析json。试试这个,它将返回一个 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();
或者如果你想要一个 JArray,你必须将 JObject[] 转换为 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));
关于c# - 如何过滤JArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72338028/