Java return JSONArray

匿名 (未验证) 提交于 2019-12-03 09:13:36

问题:

I'm trying to create a jsonarray from a Map in java. I'm passing it in to a javascript variable. But i don't know why the mac and status are blank, any help much appreciated.

what i need:

[{"12345":{"mac":"FFFFFFFF", "status":"ON"}] 

What i am getting with my current code:

[{"12345":{}] 

Here is my code,

public class Details {  public JSONArray getResult() {     return JSONArray.fromObject(this.det); } public Map det = new HashMap();  public results() {    ResultSet rs;    det.put(rs.getString(1), new NodeDetails(rs.getString(2), rs.getString(3)); } class NodeDetails {     public final String MAC;     public final String status;      public NodeDetails(final String ma,final String st) {         this.MAC = ma;         this.status = st;     }   } } 

回答1:

Do you have any limitation on any library? I mean are you using JSON library from http://org.json or which library?

Following is the code that I've tried using JSON library from http://org.json:

public class Test {      public static class NodeDetails {         public final String MAC;         public final String status;          public NodeDetails(final String ma, final String st) {             this.MAC = ma;             this.status = st;         }     }      public static void main(String[] args) throws Exception {         Map<String, NodeDetails> map = new HashMap<String, NodeDetails>();         // do something with you ResultSet? and populate the map ;)         map.put("12345", new NodeDetails("FFFFFF", "ON"));          JSONObject jsonMap = new JSONObject();         for (Map.Entry<String, NodeDetails> entry : map.entrySet()) {             JSONObject object = new JSONObject();             object.put(entry.getValue().MAC, entry.getValue().status);             jsonMap.put(entry.getKey(), object);         }          JSONArray jsonArray = new JSONArray();         jsonArray.put(jsonMap);          System.out.println(jsonArray.toString());      } } 

You can read more about the API here: http://json.org/java/



回答2:

JsonArray.fromObject-- Creates a JSONArray. Inspects the object type to call the correct JSONArray factory method. Accepts JSON formatted strings, arrays and Collections.

And Map which you are passing is not JSON formatted. So try using add() method on JsonArray Or put() method on JsonObject.



文章来源: Java return JSONArray
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!