首页 > 解决方案 > 在 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");
                

            }
        }
    }

标签: java

解决方案


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.

推荐阅读