gpt4 book ai didi

java - 将字符串与 JSON 字符串属性进行比较

转载 作者:行者123 更新时间:2023-12-02 07:14:03 26 4
gpt4 key购买 nike

我有一个 JSON 字符串 -

[{"lv":[{"v":{"nt":"10;1341943000000","userId":622},"cn":0},
{"v":{"nt":"20;1234567890123","userId":622},"cn":0},
]

在此 JSON 字符串中,我将使用 userId 作为每个值的属性。在单个 JSON 字符串中,我可能有 10 个 userId 属性或 15 个 userId 属性。 userId 总会有一些数字。

每个 JSON 字符串在 userId 中都有相同的编号。如果您看到上面的 JSON 字符串,我将 622 作为每个 userId 的编号。

现在我尝试将 id 与 JSON 字符串中的 userId 进行比较。我从其他方式获取 id 值,就像这样-

final int id = generateRandomId(random);

因此 id 值应与单个 JSON 字符串中的所有 userId 属性匹配。

我将所有 JSON 字符串存储在 colData List<String> 中。目前我正在尝试使用 id 类的 userId 方法将 containsString 进行匹配,我认为这是不正确的,因为一旦它找到一个匹配项,那么 if 条件就会变为 true (这是错误的)。

Single JSON String 中可能存在 20 userId properties,并且 19 userId valuesid 匹配,但其中一个 userId 属性值不相同。因此,该用例将在我的下面的代码中失败。那么我怎样才能实现这个问题定义

for (String str : colData) {

if (!str.contains(String.valueOf(id))) {

// log the exception here
handleException(ReadConstants.ID_MISMATCH, Read.flagTerminate);

}
}

感谢您的帮助。

最佳答案

一种方法是使用 Matcher

public class Uid {
private static final Pattern USER_ID_PATTERN = Pattern.compile("userId\":\\d+");
private static final String GENERATED_USER_ID = "userId\":622";
public static void main(String[] args) {

List<String> jsonData = new ArrayList<String>();
jsonData.add("[{\"lv\":[{\"v\":{\"nt\":\"10;1341943000000\",\"userId\":621},\"cn\":0},{\"v\":{\"nt\":\"20;1234567890123\",\"userId\":622},\"cn\":0},]"); // this string contains multiple uids

for (String s : jsonData) {
Matcher matcher = USER_ID_PATTERN.matcher(s);
while (matcher.find()) {
String currentUid = matcher.group();
if (!currentUid.equals(GENERATED_USER_ID))
System.out.println("LOG exception, " + currentUid + " doesn't exists");

}
}
}
}

关于java - 将字符串与 JSON 字符串属性进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com