C#——获取,然后比较来自 JSON 字符串的值

标签 c# json

我需要从 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 wildcards将搜索限制在您的 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();
    

    这里的..是一个通配符,意思是“递归下降”。

使用来自 this question 的以下 IsOrdered 扩展通过 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;
    }
}

关于C#——获取,然后比较来自 JSON 字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30900818/

相关文章:

c# - System.Net.Http.Httpexception 一夜之间失败; "Left with 0 client certificates to choose from."

c# - 使用c#从数组中随机选择4个元素

json - 如何使用 awk/sed 在两行之间添加新的文本行? (在文件中)

python - 如何在 python 中的 json.load 期间编辑/重命名键?

json - 使用 NodeJS 进行深度 xml 解析为 csv

c# - 当 Action 重载可用时,为异步 lambda 函数显式使用 Func<Task>

c# - 如何避免在服务层上引用 Entity Framework 的需要?

c# - 如何将 wpf ListBox 的 ItemTemplate 嵌入到 Window 的资源中?

python - 如何不断检查 JSON 文件是否在 Python 中更新?

Python - 将超大 (6.4GB) XML 文件转换为 JSON