简体   繁体   English

C# - 获取,然后比较JSON字符串中的值

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

I need to extract values from a JSON string so I can compare them. 我需要从JSON字符串中提取值,以便我可以比较它们。 I only need to verify that they are in order (ascending/descending). 我只需要验证它们是否有序(升序/降序)。 I was going to check the first and second 'choices' and compare. 我打算检查第一个和第二个“选择”并进行比较。 I don't anything more advanced. 我没有更高级的东西。

EDIT/UPDATE: How could I use wildcards (*) in this type of query to skip having 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"
          }
        }
      }
    }
  }
}   

The reason you are having some difficulty may be that the two "choicec" properties are not at the same depth in the JSON hierarchy. 您遇到一些困难的原因可能是两个"choicec"属性在JSON层次结构中的深度不同。 The first is underneath "round2" while the second is not. 第一个是"round2"而第二个不是。 Thus straightforward indexing will not work. 因此,简单的索引不起作用。

Assuming that you are able to use Json.NET , your options are: 假设您能够使用Json.NET ,您的选择是:

  1. Use Descendants to look for all properties named "choicec" and check if they are ordered: 使用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. Use SelectTokens with JsonPath wildcards to restrict the search to a portion of your JSON, if there happen to be other properties named "choicec" in your hierarchy that are not relevant to the query: 使用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(); 

    Here .. is a wildcard meaning "recursive descent". 这里..是一个通配符,意思是“递归下降”。

Using the following IsOrdered extension from this question by Mikkel R. Lund : 使用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