簡體   English   中英

C# - 獲取,然后比較JSON字符串中的值

[英]C# — Get, then compare values from JSON string

我需要從JSON字符串中提取值,以便我可以比較它們。 我只需要驗證它們是否有序(升序/降序)。 我打算檢查第一個和第二個“選擇”並進行比較。 我沒有更高級的東西。

編輯/更新:我如何在這種類型的查詢中使用通配符(*)來跳過每個段?

               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"
          }
        }
      }
    }
  }
}   

您遇到一些困難的原因可能是兩個"choicec"屬性在JSON層次結構中的深度不同。 第一個是"round2"而第二個不是。 因此,簡單的索引不起作用。

假設您能夠使用Json.NET ,您的選擇是:

  1. 使用Descendants查找名為"choicec" 所有屬性並檢查它們是否已訂購:

      var obj = JObject.Parse(json); bool inOrder = obj.Descendants() .OfType<JProperty>() .Where(p => p.Name == "choicec") .Select(p => (int)p.Value) .IsOrdered(); 
  2. 使用SelectTokensJsonPath通配符來限制搜索到你的JSON的一部分,如果碰巧是其他屬性命名為"choicec"層次結構中的不相關的查詢:

      // 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(); 

    這里..是一個通配符,意思是“遞歸下降”。

使用Mikkel R. Lund的 這個問題的以下IsOrdered擴展:

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM