C # - Get and then compare values ​​from a JSON string

I need to extract values ​​from a JSON string so that I can compare them. I only need to check that they are in order (up / down). I was going to check the first and second "choices" and compare. I am no more advanced.

EDIT / UPDATE: How can I use wildcards (*) in this type of query to skip each segment?

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" } } } } } } 
+6
source share
1 answer

The reason you are having difficulty may be because the two "choicec" properties are not at the same depth in the JSON hierarchy. The first is under "round2" and the second is not. Thus, simple indexing will not work.

Assuming you can use Json.NET , your options are:

  • Use Descendants to search for all properties named "choicec" and check if they are ordered:

      var obj = JObject.Parse(json); bool inOrder = obj.Descendants() .OfType<JProperty>() .Where(p => p.Name == "choicec") .Select(p => (int)p.Value) .IsOrdered(); 
  • Use SelectTokens with SelectTokens Wildcards to restrict the search to part of your JSON if there are other properties in your hierarchy named "choicec" that are not relevant to the 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(); 

    Here .. is a wildcard meaning "recursive descent."

Using the following IsOrdered extension from this question from 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
source

Source: https://habr.com/ru/post/989300/


All Articles