这是我的 json 响应之一。我需要获取 href 的值。我不知道 items 数组重复的次数。有没有办法解析这些类型的 json 数组。
{"batch_header":
{"payout_batch_id":"123"},
"items":[
{"transaction_status":"PENDING",
"payout_batch_id":"56",
"links":[
{"href":"link"}
]}
],
"items":[
{"transaction_status":"PENDING",
"payout_batch_id":"78",
"links":[
{"href":"link"}
]
}
]
}
这是我尝试过的代码。该代码仅适用于第一个循环,然后就中断了。
JSONObject obj = new JSONObject(response);
JSONArray dataOuter = obj.getJSONArray("items");
for (int i = 0; i < dataOuter.length() ; i++ ) {
JSONObject jObject1 = dataOuter.getJSONObject(i);
logger.info(" Items "+jObject1);
JSONArray dataInner = jObject1.getJSONArray("links");
for (int j = 0; j < dataInner.length() ; j++ ) {
JSONObject jItem = dataInner.getJSONObject(i);
responseURL = jItem.getString("href");
}
}
最佳答案
我建议使用JsonPath适合您的用例的库。通过该库,您可以使用 JsonPath expressions在Java中提取信息。
代码如下所示:
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import java.util.List;
public class JsonPathExample {
public static void main(String[] args) {
String myJson = "{\n" +
" \"batch_header\": {\n" +
" \"payout_batch_id\": \"123\"\n" +
" },\n" +
" \"items\": [\n" +
" {\n" +
" \"transaction_status\": \"PENDING\",\n" +
" \"payout_batch_id\": \"56\",\n" +
" \"links\": [\n" +
" {\n" +
" \"href\": \"link1\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"transaction_status\": \"PENDING\",\n" +
" \"payout_batch_id\": \"78\",\n" +
" \"links\": [\n" +
" {\n" +
" \"href\": \"link2\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
String myPath = "$['items'][*]['links'][*]['href']";
DocumentContext jsonContext = JsonPath.parse(myJson);
List<String> jsonPathResult = jsonContext.read(myPath);
System.out.println(jsonPathResult);
}
}
输出:[“link1”,“link2”]
P.D.:您的示例 json 无效,因为它包含两个 items
。我需要修改它。
关于java - 如何解析 Json 对象中具有相同名称的多个 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61797733/