java - 在 JSON 数组中搜索特定值
问题描述
我有一个我正在创建的 JSON 数组,并且可以是可变长度的
String oktas =
"{[{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"},{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"}]}";
在此之后,我正在执行一个 API 调用,其中我需要检查上述帐号是否存在。如果是这样,那么我需要根据我的 JSON 数组更新我的 API 调用中的键值。
我的问题是我可以通过将 API 调用转换为列表来迭代它,但我不想创建另一个循环来迭代我的 JSON 数组,因为它会增加复杂性。有什么办法可以做到这一点。以下是我尝试过的,但对我不起作用。
try {
String oktas =
"{{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"},{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"}}";
List<Settings> Settings = getSettings(user);
if (Settings != null && !Settings.isEmpty()) {
for (Settings paperless : Settings) {
// check if account number present in JSON array is present in API call
if (oktas.contentEquals(paperless.getAccountNumber())) {
paperless.setPaperless(true); //set them based on my JSON array
paperless.setEmailable(true);
paperless.setUpdateFlag("B");
}
}
}
解决方案
One simple way would be to convert the string to a JSON Array and then use it in anyway you like:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Test
{
public static void main(String[] args) throws JSONException
{
String oktas =
"{{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"},{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"}}";
JSONArray jsonArr = new JSONArray(oktas);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Download java-json.jar from here, which contains org.json.JSONArray
http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip
Unzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.
推荐阅读
- image - 当计时器到达某个时间时如何完成一个动作
- powershell - 使用 Start-Process 运行 VBScript
- c - 为什么这个程序只打印第一个字符?
- python - 如何在 django-registration 中设置注销 url?
- javascript - 你如何制作一个非交互的复选框,并且仅在变量是时才检查?
- python - 带有列表的 For 循环
- r - 如何使用剪切函数获取列中没有值的 NA 值标签?
- node.js - 如何从查询中删除 CubeJS 默认的 Group By 子句
- jmeter - '%20/' 被添加到示例请求 URL
- elasticsearch - elasticsearch的设置主管