java中的JSON解析错误

时间:2015-09-29 08:50:40

标签: java json

我在jsp中创建一个JSON。

JSONObject mainObj = new JSONObject();
  JSONObject json1=null;
  JSONArray jarr =new JSONArray();



  String email = request.getParameter("EMAIL");

  cc = new MySQLConnection();

String query = "SELECT * FROM CLIENTS ";
try{
conn =cc.db();
stmtt =conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmtt.executeQuery(query);  
while(rs.next()){
    json1 = new JSONObject();

    json1.put("ID", rs.getString("ID"));
    json1.put("C_NAME", rs.getString("C_NAME"));
    json1.put("EMAIL", rs.getString("EMAIL"));
    json1.put("COMPANY", rs.getString("COMPANY"));
    json1.put("CODE", rs.getLong("CODE"));
    json1.put("VALID_TILL", rs.getString("VALID_TILL"));

    jarr.put(json1);
    mainObj.put("CLIENTS", (Object) jarr);

    mainObj.put("SUCCESS", new java.lang.Integer(1));
    out.println(mainObj.toString());


}


}
catch(SQLException ex){System.out.println(ex);}
finally{try{stmtt.close(); rs.close();conn.close();} catch(SQLException ex){System.out.println(ex);} }

我检查输出here给出了解析错误。

Parse error on line 12:
... 0        }    ]}{    "SUCCESS": 1,
--------------------^
Expecting 'EOF', '}', ',', ']'

我是java中的JSON新手,请指导我获得正确的输出。在PHP中我得到了正确的输出。

{"CLIENTS":[{"CLIENTS":[], "EMAIL":"asomi@gmail.com", "C_NAME":"choladhara", "COMPANY":"Multi Tech Systems", "CODE":"0", "VALID_TILL":"", "SL":"32"} ],"SUCCESS":1}

有人可以指导我获得预期的输出吗?

2 个答案:

答案 0 :(得分:0)

更改完成json数组构建必须在while循环

之后放入mainobj
 while(rs.next()){
        json1 = new JSONObject();

        json1.put("ID", rs.getString("ID"));
        json1.put("C_NAME", rs.getString("C_NAME"));
        json1.put("EMAIL", rs.getString("EMAIL"));
        json1.put("COMPANY", rs.getString("COMPANY"));
        json1.put("CODE", rs.getLong("CODE"));
        json1.put("VALID_TILL", rs.getString("VALID_TILL"));

        jarr.put(json1);   


    }
    mainObj.put("CLIENTS", (Object) jarr);
        mainObj.put("SUCCESS", new java.lang.Integer(1));
        out.println(mainObj.toString());

答案 1 :(得分:0)

看起来你应该将对象添加到数组中并将循环后的数组添加到主JSON对象中,如下所示:

while(rs.next()){
     json1 = new JSONObject();

     ...


     jarr.put(json1);

}

mainObj.put("CLIENTS", (Object) jarr);

mainObj.put("SUCCESS", new java.lang.Integer(1));
out.println(mainObj.toString());