Ho un oggetto JSON (NewtonSoft.JObject). Esso contiene diverse voci in questo formato:Verificare se esiste una chiave in NewtonSoft JObject C#
{
"id": "b65ngx59-2c67-4f5b-9705-8525d65e1b8",
"name": "TestSample",
"versions": []
},
{
"id": "8acd8343-617f-4354-9b29-87a251d2f3e7",
"name": "template 2",
"versions": [
{
"id": "556ng956-57e1-47d8-9801-9789d47th5a5",
"template_id": "8acd8343-617f-4354-9b29-87a251d2f3e7",
"active": 1,
"name": "1.0",
"subject": "<%subject%>",
"updated_at": "2015-07-24 08:32:58"
}
]
}
Nota: Solo un esempio.
Ho scritto un codice in modo che ricevo gli ID di un elenco:
List<JToken> templateIdList = jObj.Descendants()
.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id")
.Select(p => ((JProperty)p).Value)
.ToList();
Nota: jObj è l'oggetto JSON
La lista di uscita è:
[0] - b65ngx59-2c67-4f5b-9705-8525d65e1b8
[1] - 8acd8343-617f-4354-9b29-87a251d2f3e7
[2] - 556ng956-57e1-47d8-9801-9789d47th5a5
Fornisce tutti gli id. Ora voglio aggiungere una condizione al linq in modo che solo gli ID_temperie contenente attivo con valore = 1 in esse deve essere compilato nell'elenco.
L'output desiderato:
[0] - 8acd8343-617f-4354-9b29-87a251d2f3e7
Quali modifiche devo apportare alla query LINQ per ottenere questo?
EDIT: il codice completo è
public bool CheckIfTemplateExists(string template)
{
bool exists = false;
//web service call to retrieve jsonTemplates
JObject jObj = JObject.Parse(jsonTemplates);
List<JToken> templateIdList = jObj.Descendants()
.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "id")
.Select(p => ((JProperty)p).Value)
.ToList();
if(templateIdList.IndexOf(template) != -1)
{
exists = true;
}
return exists
}
Le jsonTemplates nel codice di cui sopra è una stringa di formato:
{"templates":
[{"id":"b65cae59-2c67-4f5b-9705-07465d65e1b8",
"name":"TestSample","versions":[]},
{"id":"8edb8343-617f-4354-9b29-87a251d2f3e7",
"name":"Template1",
"versions":[{"id":"556bb956-57e1-47d8-9801-9388d47cc5a5",
"template_id":"8edb8343-617f-4354-9b29-87a251d2f3e7",
"active":1,
"name":"1.0","subject":"\u003c%subject%\u003e",
"updated_at":"2015-07-24 08:32:58"}]}
Ciao grazie per aver risposto .. Ho provato il tuo codice ma sta dando un errore " Impossibile accedere al valore figlio su Newtonsoft.Json.Linq.JProperty. " – nitinvertigo
Potresti condividere l'intero frammento di codice che non funziona? Proverò a sistemare. –
Il compilatore dà un errore quando raggiunge la query linq che hai dato a – nitinvertigo