[英]Loop through each element in array
我正在嘗試遍歷下面的 JSON 格式對象,我有下面的代碼
private Integer k1;
private List<Integer> k2 = new ArrayList<Integer>();
// getter setters
將映射到 POJO 請求的傳入 JSON 對象
[{"k1":1,"k2":[2,3,4]},{"k1":2,"k2":[5,6,7]}]
我正在嘗試遍歷請求數據並獲取 k1 和 k2 的值。 我怎樣才能做到這一點。 非常感謝您提供的任何幫助。
我已經嘗試過下面的代碼,但是有沒有更好的方法來使用流來實現這一點
for (Map.Entry<String, Integer> entry : map.entrySet()) {
}
我想迭代每個元素以獲取 k1 的值,然后 k2 以獲取所有值。 我很困惑如何遍歷外部數組,然后從 k2 的內部數組中獲取值。
預期產出
select * from table where col1=1 and col2=2;
select * from table where col1=1 and col2=3;
select * from table where col1=1 and col2=4;
select * from table where col1=2 and col2=5;
select * from table where col1=2 and col2=6;
//Similarly all values iterated and made db call each time
使用 col1 的 k1 和 col2 的 k2 的值調用 DB
使用 objectMapper 將您的 json 轉換為 pojo。 這將是一個列表。 然后遍歷列表並調用相應的 getter 來獲取值
class Custom{
private Integer k1;
private List<Integer> k2 = new ArrayList<Integer>();
}
String json = "[{\"k1\":1,\"k2\":[2,3,4]},{\"k1\":2,\"k2\":[5,6,7]}]";
ObjectMapper mapper = new ObjectMapper();
List<Custom> customsList = Arrays.asList(mapper.readValue(json, Custom[].class));
customsList.stream().forEach(cl -> System.out.println(cl.getK1()+":"+cl.getK2()));
另一種方法是使用Gson
。
Gson gson = new GsonBuilder().create();
List<Custom> list = gson.fromJson(json, new TypeToken<List<Custom>>(){}.getType());
現在正如@NikitaBansal所提到的,您所要做的就是遍歷列表並構造您的 SQL 語法。
for(Custom obj : list){
for(Integer i : obj.k2 ){
System.out.println("K1 " + c.k1+ " :: K2 "+i);
//your code
}
}
這完全取決於您,您將如何遍歷它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.