如何在Postman中同时展示多个JSON对象 修复Java接口仅返回最后一条数据问题
问题原因
你当前的代码使用单个JSONObject变量obj3接收每次checkStock的返回值,每次循环都会覆盖上一次的结果,所以最终返回的只有最后遍历到的ACC标的的查询结果。
解决方案
把所有标的的查询结果存入JSONArray统一返回即可,修改后的代码如下:
public String doStock(JsonObject SymbolName) throws Exception { JSONObject obj2 = new JSONObject(SymbolName); JSONArray jsonArray = (JSONArray) obj2.get("SymbolName"); // 用JSONArray存储所有标的的查询结果 JSONArray resultArray = new JSONArray(); Object obj = null; System.out.println(""); System.out.println("Symbol Name: "); //Iterating the contents of the array for(int i = 0; i < jsonArray.length(); i++){ obj = jsonArray.get(i); System.out.println(obj); // 把当前标的的查询结果添加到结果数组 resultArray.put(checkStock(obj.toString())); } // 返回所有结果 return resultArray.toString(); }
可选优化
如果需要符合更通用的接口返回规范,可以在外层套一层自定义对象:
public String doStock(JsonObject SymbolName) throws Exception { JSONObject obj2 = new JSONObject(SymbolName); JSONArray jsonArray = (JSONArray) obj2.get("SymbolName"); JSONArray resultArray = new JSONArray(); Object obj = null; System.out.println(""); System.out.println("Symbol Name: "); for(int i = 0; i < jsonArray.length(); i++){ obj = jsonArray.get(i); System.out.println(obj); resultArray.put(checkStock(obj.toString())); } // 外层套自定义对象返回 JSONObject finalResult = new JSONObject(); finalResult.put("code", 200); finalResult.put("msg", "查询成功"); finalResult.put("data", resultArray); return finalResult.toString(); }
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

