我在自己的一端创建了一个JSON数组,它的长度可以是可变的
String oktas =
"{[{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"},{\"accountNumber\" : \"13176704\", \"paperless\" : \"true\", \"emailable\" : \"true\"}]}";在此之后,我正在执行一个API调用,其中我需要检查上面的账号是否存在。如果是这样,那么我需要根据JSON数组更新API调用中的键值。
我的问题是,我可以通过将API调用转换为list来迭代它,但我不想创建另一个循环来迭代我的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");
}
}
}发布于 2021-06-24 21:37:15
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.https://stackoverflow.com/questions/68116547
复制相似问题