比较和匹配嵌套的JSON值

时间:2019-02-14 16:31:22

标签: c# .net json linq

我正在尝试创建一个函数,该函数将比较JSON列表中的嵌套值。 它需要将final.model的值与current.model进行比较。当模型匹配时,需要从final.qty中减去current.qty,然后从qty = 0的列表中删除所有模型。

我已经尝试了许多不同的方法,但是无法将最终模型与当前模型进行比较。

{"final": [
    {"model": "RRUS-11", "qty": "4"},
    {"model": "RFS ATM192012-0", "qty": "2"},
    {"model": "WCS-IMFQ-AMT-43", "qty": "8"},
    {"model": "SBNHH-1D65A", "qty": "9"} ], 
"current": [
   {"model": "SBNHH-1D65A", "qty": "6"},
    {"model": "RRUS-32 B2", "qty": "4"},
    {"model": "WCS-IMFQ-AMT-43", "qty": "6"},
    {"model": "RRUS-11", "qty": "4"} ]
}

public class Container
        {
            public string model { get; set; }
            public int? qty { get; set; }
        }

var results = JsonConvert.DeserializeObject<Dictionary<string, List<Container>>>(requestBody);

var DetermineProposed = results.Where(x => !string.IsNullOrWhiteSpace(x.Key))
        .Select(x => new { x.Value })

        .ToList();

return new OkObjectResult(DetermineProposed);

This is what the returned DetermineProposed should look:
[ {"model": "WCS-IMFQ-AMT-43", "qty": "2"},
  {"model": "SBNHH-1D65A", "qty": "3"} ]

1 个答案:

答案 0 :(得分:0)

JSON是一个字符串。解析后,您将不再使用JSON。当前代码甚至没有检索到两个列表,更不用说比较它们了。

数量上的差异可以使用LINQ并根据模型将两个列表结合起来:

var results = JsonConvert.DeserializeObject<Dictionary<string, List<Container>>>(json);

var final=results["final"];
var current=results["current"];

var diffs=from f in final
           join c in current on f.model equals c.model
           let diff=new Container{model=f.model,qty=f.qty-c.qty}
           where diff.qty!=0
           select diff;

结果将是:

model            qty
WCS-IMFQ-AMT-43  2 
SBNHH-1D65A      3