当比较一个数组的值与另一个数组时,jtoken.selecttokens问题

时间:2017-06-08 09:39:14

标签: c# json json.net jsonpath

我需要使用以下逻辑获取金额。如果product.ID等于stores.ID,则获取product.amount JSON

{
 "stores": [
{
  "ID": 17736791,
  "Name": "ABC"
},
{
  "ID": 154423041,
  "Name": "XYZ"
}
],
"product": [
{
  "ID": 154423041,
  "Amount": 19865337
}
]
}

我正在使用jtoken.selecttoken来获取数据,如下所示。但它因为无法读取查询运算符而抛出错误。

string path = ToJsonPath(product[ID=stores[*].ID].Amount);
var data= token.SelectTokens(path)

更新,ToJsonPath

public string ToJsonPath(string query)
    {
        string normalizedQuery = query.Replace(DoubleQuotes, SingleQuotes);

        StringBuilder jsonPath = new StringBuilder();
        jsonPath.Append(string.Concat(RootElement, ChildOperator));
        jsonPath.Append(normalizedQuery);

        MatchCollection expressions = Regex.Matches(normalizedQuery, ExpressionRegexPattern);

        StringBuilder expression = new StringBuilder();
        for (int i = 0; i < expressions.Count; i++)
        {
            if (!Regex.IsMatch(expressions[i].Value, OperatorRegexPattern))
            {
                continue;
            }

            expression.Length = 0;
            expression.Capacity = 0;

            expression.Append(expressions[i].Value);
            jsonPath.Replace(expression.ToString(), Placeholder);

            string[] expressionTerms = expression.ToString()
                .Split(new[] { AndOperator, OrOperator }, StringSplitOptions.RemoveEmptyEntries)
                .Select(t => t.Trim())
                .ToArray();

            foreach (string expressionTerm in expressionTerms)
            {
                expression.Replace(expressionTerm, Placeholder);
                expression.Replace(Placeholder, string.Concat(CurrentElement, ChildOperator, expressionTerm));
            }

            string expressionWithEscapedOperators = Regex.Replace(expression.ToString(), OperatorRegexPattern, " $& ");
            string expressionWithDoubleEqualOperators = Regex.Replace(expressionWithEscapedOperators, EqualOperatorPattern, "$&$&");

            string jsonExpression = string.Format(JsonExpressionTemplate, expressionWithDoubleEqualOperators);
            jsonPath.Replace(Placeholder, jsonExpression);
        }

        return jsonPath.ToString();
    }

1 个答案:

答案 0 :(得分:0)

不确定JSONPath但使用LINQ to JSON这可以通过以下方式实现:

var obj = JObject.Parse(json);
var storeIds = obj["stores"]
    .Select(s => (int)s["ID"])
    .ToList();
var selectedAmount = obj["product"]
    .Where(p => storeIds.Contains((int)p["ID"]))
    .Select(p => (int)p["Amount"])
    .FirstOrDefault();

演示:https://dotnetfiddle.net/CRn5Az