我只有以下格式的 JSON 请求:(原始 JSON 很大,因此分享博客中的示例)
示例请求:
{
"testData": [
{
"firstName": "Lokesh",
"lastName": "Gupta",
"website": "howtodoinjava.com"
},
{
"firstName": "Brian",
"lastName": "Schultz",
"website": "example.com"
}
]
}
我只有下面的方法,它应该获取上面 JSONArray 的每个索引。上面的请求应该返回 size() == 2。我只想在每次迭代中打印整个 array[0] 和 array[1] ,如下所示。
public static void constructJSON(CheckoutDTO result)throws Exception
{
String jsonBody = result.getJson();
JSONObject object = parseAndReturnObj(jsonBody);
JSONArray array= (JSONArray) object.get("testData");
int index=0;
for(int i=0;i<array.size();i++)
{
index++;
JSONObject objects = (JSONObject) array.get("");
Sysout(objects); // Here I just want to print the array[0] index as entire JSONObject.
}
}
}
上面的代码我只想打印数组的每个索引。就像第一次迭代一样,我只想打印如下:
数组[0]:
{
"firstName": "Lokesh",
"lastName": "Gupta",
"website": "howtodoinjava.com"
}
第二次迭代应该打印如下:
数组[1]:
{
"firstName": "Brian",
"lastName": "Schultz",
"website": "example.com"
}
上述请求可能有“n”个数组[n]。我只想按照上面的格式在 for 循环中打印 Systout(Objects)。
使用 simplejson 库读取JSONObject。
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
任何人都可以帮助我实现这一目标吗?
最佳答案
您可以简单地编写System.out.println(object);
。 JSONObject
的 toString()
方法会自动将其转换为json。您的 for
循环可以修改为
for (int i = 0; i < array.size(); i++) {
index++;
JSONObject object = (JSONObject) array.get(i);
System.out.println(object);
}
关于java - 如何使用简单的 JSON 库基于索引获取整个 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60269112/