2015-06-17 14 views
6

Ho bisogno di estrarre i valori da una stringa JSON per poterli confrontare. Ho solo bisogno di verificare che siano in ordine (crescente/decrescente). Stavo per controllare la prima e la seconda "scelta" e confrontare. Non ho niente di più avanzato.C# - Ottieni, quindi confronta i valori della stringa JSON

MODIFICA/AGGIORNAMENTO: Come è possibile utilizzare i caratteri jolly (*) in questo tipo di query per ignorare ogni segmento?

   string one = (string)o[this.Context[*WILDCARD*]["cid1"]].ToString(); 


      /* this works, but has too many [] 
      string one = (string)o[this.Context["partner"]] 
       [this.Context["campaign"]] 
       [this.Context["segment1"]] 
       [this.Context["segment2"]] 
       [this.Context["qid2"]] 
       ["community"] 
       [this.Context["cid1"]].ToString(); 
      */ 


{ 
    "partner": { 
    "campaign": { 
     "round1": { 
     "round2": { 
      "def123": { 
      "community": { 
       "choicec": 28 
      }, 
      "user": { 
       "choice": "choicec", 
       "writeDateUTC": "2015-06-15T17:21:59Z" 
      } 
      } 
     }, 
     "abc321": { 
      "community": { 
      "choicec": 33 
      }, 
      "user": { 
      "choice": "choicec", 
      "writeDateUTC": "2015-06-15T17:21:59Z" 
      } 
     } 
     } 
    } 
    } 
} 
+0

Suona come un progetto cool! Quello che sembra essere il problema? – cubrr

+0

Ive ha provato a utilizzare LINQ, Jtoken, Jpath e altri e tutti falliscono o ritornano vuoti. Quindi cerca di raggiungere la community –

+0

Prova questo con JSON.NET (dovrai usare 'using Newtonsoft.Json' dopo aver aggiunto il pacchetto Nuget):' dynamic d = JsonSerializer.Deserialize (yourJsonString); 'quindi usa' d.partner.campaign.round1.def123.community.choicec' per accedere al numero di scelta. – cubrr

risposta

1

La ragione si stanno avendo qualche difficoltà può essere che le due "choicec" proprietà non sono alla stessa profondità della gerarchia JSON. Il primo è sotto "round2" mentre il secondo no. Così l'indicizzazione semplice non funzionerà.

Supponendo che si è in grado di utilizzare Json.NET, le opzioni sono:

  1. Usa Descendants cercare tutte proprietà denominate "choicec" e verificare se sono ordinate:

    var obj = JObject.Parse(json); 
        bool inOrder = obj.Descendants() 
         .OfType<JProperty>() 
         .Where(p => p.Name == "choicec") 
         .Select(p => (int)p.Value) 
         .IsOrdered(); 
    
  2. Utilizzare SelectTokens con JsonPath wildcards per limitare la ricerca a una parte del JSON, se ci sono altre proprietà denominate "choicec" nella gerarchia che non sono rilevanti per la query:

    // Find all properties named "choicec" under "community" recursively under "campaign" under "partner". 
        bool inOrder = obj.SelectTokens("partner.campaign..community.choicec") 
         .Select(o => (int)o) 
         .IsOrdered(); 
    

    Qui .. è un jolly che significa "discesa ricorsiva".

Utilizzando il seguente IsOrdered estensione da this question da Mikkel R. Lund:

public static class EnumerableExtensions 
{ 
    // Taken from http://stackoverflow.com/questions/19786101/native-c-sharp-support-for-checking-if-an-ienumerable-is-sorted 
    public static bool IsOrdered<T>(this IEnumerable<T> collection, IComparer<T> comparer = null) 
    { 
     if (collection == null) 
      throw new ArgumentNullException(); 
     comparer = comparer ?? Comparer<T>.Default; 

     using (var enumerator = collection.GetEnumerator()) 
     { 
      if (enumerator.MoveNext()) 
      { 
       var previous = enumerator.Current; 

       while (enumerator.MoveNext()) 
       { 
        var current = enumerator.Current; 

        if (comparer.Compare(previous, current) > 0) 
         return false; 

        previous = current; 
       } 
      } 
     } 

     return true; 
    } 
} 
+1

Incredibile, completo e utile. –