【问题标题】:C# -- Get, then compare values from JSON stringC#——获取,然后比较来自 JSON 字符串的值
【发布时间】:2017-09-03 04:46:41
【问题描述】:

我需要从 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"
          }
        }
      }
    }
  }
}   

【问题讨论】:

  • 听起来是个很酷的项目!似乎是什么问题?
  • 我尝试过使用 LINQ、Jtoken、Jpath 等,但都失败或返回空。所以我接触到社区
  • 用 JSON.NET 试试这个(添加 Nuget 包后需要using Newtonsoft.Json):dynamic d = JsonSerializer.Deserialize(yourJsonString); 然后使用d.partner.campaign.round1.def123.community.choicec 访问选项编号。
  • 为什么是dynamic?一定有一个具体的课程。
  • 您的 JSON 中没有 "cid1" 属性。只是为了确认一下,您想比较 "choicec": 28"choicec": 33 属性的值以检查它们是否正常?

标签: c# json


【解决方案1】:

您遇到一些困难的原因可能是两个 "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. 如果您的层次结构中碰巧有其他名为 "choicec" 的属性与查询无关,请使用 SelectTokensJsonPath wildcards 将搜索限制为 JSON 的一部分:

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

【讨论】:

  • 惊人的、彻底的和乐于助人的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 2019-10-08
  • 2013-06-04
  • 2013-02-05
相关资源
最近更新 更多