首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JSON数组中搜索特定值

在JSON数组中搜索特定值
EN

Stack Overflow用户
提问于 2021-06-24 21:18:10
回答 1查看 39关注 0票数 0

我在自己的一端创建了一个JSON数组,它的长度可以是可变的

代码语言:javascript
复制
String oktas =
    "{[{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"},{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"}]}";

在此之后,我正在执行一个API调用,其中我需要检查上面的账号是否存在。如果是这样,那么我需要根据JSON数组更新API调用中的键值。

我的问题是,我可以通过将API调用转换为list来迭代它,但我不想创建另一个循环来迭代我的JSON数组,因为这会增加复杂性。我有没有办法做到这一点。下面是我尝试过的方法,但对我不起作用。

代码语言:javascript
复制
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");
                

            }
        }
    }
EN

回答 1

Stack Overflow用户

发布于 2021-06-24 21:37:15

代码语言:javascript
复制
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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68116547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档