java - 如何在循环中填充 json 数组

标签 java json

我想从表中获取数据并使用 json 对象将该数据填充到数组中。

我已经完成了硬编码示例,该示例工作正常,但现在我想使用循环填充数据。但使用循环会导致数据重叠。意味着最后只有 1 行输出。

JSONObject items = new JSONObject();
JSONArray itemlines = new JSONArray();

Statement getLines = dbconnection.createStatement();
ResultSet LinesRS = getLines.executeQuery("SELECT 
b.line_number,b.ordered_item,b.description,b.line_quantity,
"(SELECT order_quantity_uom FROM oe_order_lines_all WHERE line_id = 
b.line_id) uom\n" +
"FROM rocell.xrcl_ns_int_quotation_details b WHERE b.header_id = 
"+getQuotationsRS.getString(1));
         while(LinesRS.next())
         {
           items.put("lineNo", LinesRS.getString(1));
           items.put("itemCode", LinesRS.getString(2));
           items.put("itemDesc", LinesRS.getString(3));
           items.put("qty", LinesRS.getString(4));
           items.put("unit", LinesRS.getString(22)); 
           itemlines.put(items);
         }



record.put("items", itemlines);

I want output like below

"items": [ { "lineNo": 1, 
             "itemCode": "IT001", 
             "itemDesc": "Bottle", 
             "qty": "3",
             "unit":"EA"},
           { "lineNo": 2, 
             "itemCode": "IT002", 
             "itemDesc": "Flask", 
             "qty": "2",
             "unit":"EA"}
         ]

最佳答案

JSONArray itemlines = new JSONArray();

Statement getLines = dbconnection.createStatement();
ResultSet LinesRS = getLines.executeQuery("SELECT 
b.line_number,b.ordered_item,b.description,b.line_quantity,
"(SELECT order_quantity_uom FROM oe_order_lines_all WHERE line_id = 
b.line_id) uom\n" +
"FROM rocell.xrcl_ns_int_quotation_details b WHERE b.header_id = 
"+getQuotationsRS.getString(1));
         while(LinesRS.next())
         { //every time this JSONObject items  is init and put into itemlines
           JSONObject items = new JSONObject();
           items.put("lineNo", LinesRS.getString(1));
           items.put("itemCode", LinesRS.getString(2));
           items.put("itemDesc", LinesRS.getString(3));
           items.put("qty", LinesRS.getString(4));
           items.put("unit", LinesRS.getString(22)); 
           itemlines.put(items);
         }



record.put("items", itemlines);

关于java - 如何在循环中填充 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58157621/

相关文章:

java - 无法实例化类型 Set

java - 激活文件夹中的所有 bundle

java - 字符串与常量错误的比较

node.js - Firestore云功能在一个字段中添加多个字段

java - GAE 端点错误 : can not access a member of class with modifiers "private"

javascript - 来自json的 Angular 日期格式

java - 如何更新 OpenJDK 的时区信息?

Java将子类实例数据传递给父类(super class)构造函数

javascript - 防止 JSON.parse 重新排列对象

asp.net - 在 WebAPI 2 中将 json 对象发送到 HttpGet 端点的正确方法