I wanna query an System.Text.Json.Nodes.JsonArray by prop value ,
Is there any JsonArray function can query JsonObject in which array index without foreach/forloop or extra libray ?
[
{"key": 1,"value": "UOB" ,"connections":["WebPOS_dropdownlist","WebIMS_dropdownlist"] ,"synced":0,"last_synced":"2024/7/16 4:26:34"},
{"key": 2,"value": "OCBC","connections":[],"synced":1,"last_synced":"2024/7/16 4:26:34" }
]
JsonArray arr= (JsonArray)JsonObject.Parse("[ rn{"key": 1,"value": "UOB" ,"connections":["WebPOS_dropdownlist","WebIMS_dropdownlist"] ,"synced":0,"last_synced":"2024/7/16 4:26:34"}, rn{"key": 2,"value": "OCBC","connections":[],"synced":1,"last_synced":"2024/7/16 4:26:34" }rn]");
//arr.Where?arr.Select?
//query condition "value" =="OCBC"
[
{"key": 1,"value": "UOB" ,"connections":["WebPOS_dropdownlist","WebIMS_dropdownlist"] ,"synced":0,"last_synced":"2024/7/16 4:26:34"},
{"key": 2,"value": "OCBC","connections":[],"synced":1,"last_synced":"2024/7/16 4:26:34" }
]
//expect return filtered jsonarray
[
{"key": 1,"value": "UOB" ,"connections":["WebPOS_dropdownlist","WebIMS_dropdownlist"}
]
//or match index
1
民麒張 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The easiest option would be to deserialize to concrete types and use LINQ to find what you want. There’s no benefit to deserializing into JsonObject or JsonArray :
public record Item(int key, string value, List<string> connections,
int synced, string last_synced);
...
var items=JsonSerializer.Deserialize<List<Item>>(jsonString);
var theItem=items.First(it=>it.value=="OCBC");
foreach(var connection in theItem.connections)
{
Console.WriteLine(connection);
}
Console.WriteLine(theItem.synced);
If you want to work with JsonArray, you can use LINQ to check specific values. There are no performance gains. You’re deserializing to a different type that’s meant for JSON manipulation
JsonArray jsonArray = (JsonArray)JsonNode.Parse(jsonString);
var theItem = jsonArray.First(it => it["value"].ToString() == "OCBC");
if (theItem["connections"] is JsonArray connections)
{
foreach(var connection in connections)
{
Console.WriteLine(connection);
}
}
Console.WriteLine(theItem["synced"]);