【问题标题】:Converting JSONArray to JSONObject [duplicate]将 JSONArray 转换为 JSONObject [重复]
【发布时间】:2018-04-10 19:52:05
【问题描述】:

我正在编写一个 REST Java 服务。我想将我的 JSONArray 转换为 JSONObject 并返回它。但是当我从浏览器点击我的休息服务时,我得到了“{}”作为输出。虽然当我尝试使用 System.out.println() 打印时,它在休息服务中打印良好;

PreparedStatement dimDelPS = null;
ResultSet dimDelRS = null;
dimDelPS = connection.prepareStatement("select * from abc");
dimDelRS = dimDelPS.executeQuery();
String dimLow=null;

while (dimDelRS.next()) {
    int total_rows = dimDelRS.getMetaData().getColumnCount();
    for (int i = 0; i < total_rows; i++) {
        org.json.JSONObject obj = new org.json.JSONObject();
        obj.put(dimDelRS.getMetaData().getColumnLabel(i + 1)
                .toLowerCase(), dimDelRS.getObject(i + 1));
        jsonArray.put(obj);
    }
}

System.out.println("json1 :"+jsonArray);

//Sample output at this stage: ["{\"employee\":\"ANTHONY.DUNNE\"}","{\"type\":\"Manager\"}"]

dimDelRS.close();
dimDelPS.close();
JSONObject jsobobject= new JSONObject();
jsobobject.put("aoColumnDefs",jsonArray);
System.out.println(jsobobject);
return jsobobject;

【问题讨论】:

  • 不,它不工作,浏览器正在显示 {}
  • 您没有提供足够的信息。据我们所知,上述代码 sn-p 与浏览器或 REST 调用无关。你在使用框架吗?整个方法是什么样的?请查看How to create a Minimal, Complete, and Verifiable example
  • 另外,谁赞成这个问题?太可怕了。
  • 我认为问题出在 json 上。你的 json 应该像 { "aoColumnDefs" : [ { "employee": "ANTHONY.DUNNE" }, { "type":"Manager" } ] }

标签: java json rest


【解决方案1】:

你不能只返回 JSONObject。

你需要确定你将它编入json。

'return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).build();'

浏览器理解字符串,而不是 java 对象。

【讨论】:

  • 请容忍我的不良格式,从手机回答。
  • 这是一个相当大的假设,即 OP 正在使用 JAX-RS。问题中没有证据支持这一点。
  • 它不工作。我只是将返回类型替换为响应,最后一行替换为您提供的内容。仍然是浏览器上的 {}。
  • 谢谢,这工作。 return Response.ok(jsobobject.toString(), MediaType.APPLICATION_JSON).build();
  • Bravo,如果可能的话,您能否更新/编辑答案和格式:P
猜你喜欢
  • 1970-01-01
  • 2016-06-05
  • 2019-08-17
  • 2011-11-03
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多