如何通过 JSON 对象列表检查键的值是否相等

How to check if the value of a key is equal through out the list of JSON Object

我正在尝试在 C# 中输入一些验证。 我有一个 JSON 对象的列表,我想添加一个验证来检查某个键的值并确保它们在数组中的所有 JSON 对象中都相同。

列表-

subtitles = [{ frameRate : '25', dropFrame: False}, { frameRate : '25', dropFrame: False}, { frameRate : '25', dropFrame: False}, { frameRate : '23', dropFrame: False}]

我想添加循环遍历每个对象的验证,并确保键 frameRate 的值在数组中是相同的。

这就是我尝试做的 - 我创建了一个空列表,然后尝试推送所有 frameRates,然后遍历它并将值与前一个进行比较。

List<string> subtitleSegmentsFrameRates = new List<string>();

            foreach (var subtitle in segmentSubtitles) 
            {
                subtitleSegmentsFrameRates.Add(subtitle.frameRate);
                    
            }

            for (int i = 0; i < subtitleSegmentsFrameRates.Count; i++) {
                if (i != 0) {
                    if (subtitleSegmentsFrameRates[i] != subtitleSegmentsFrameRates[i - 1]) {
                        throw new CustomException("Frame Rates arocss segments do not match.");
                    }
                }
            }

有更好的方法吗?

首先将您的 json 字符串转换为 JArray 并使用 .All() 检查所有元素的 frameRate 属性 是否具有相同的值。

using System;
using Newtonsoft.Json.Linq;
using System.Linq;

...
var validFrameRate = JArray.Parse(subtitles)  //Convert an Sub titles to JArray
           .All(x => x.Value<string>("frameRate") == "25");  //Check all frame rates are same or not.

Console.WriteLine(validFrameRate ? "Same frameRate in all elements" : "Different FrameRate in all elements");

.Net Fiddle


JArrayJToken 的数组,要获得实际值,您需要将 JToken 转换为其实际类型。这里我们使用 .Value<string>() 来获取 frameRate 属性 的 JToken

的值

您可以在解析输入 JArray 和 linq All 方法

后将所有项目与第一个项目进行比较
var jArray = JArray.Parse(subtitles);
bool allSame = jArray.All(j => j["frameRate"].Value<string>() == jArray[0]["frameRate"].Value<string>());

j["frameRate"]JToken 的类型,这就是为什么要在其上调用 .Value<string>() 转换为字符串的原因。

@John 也推荐的另一种方式:

bool same = jArray.Select(j => j["frameRate"].Value<string>()).Distinct().Count() == 1

检查这个 fiddle - https://dotnetfiddle.net/5xOJB5