[英]Java return JSONArray
I'm trying to create a jsonarray from a Map in java. 我正在尝试从Java中的Map创建一个jsonarray。 I'm passing it in to a javascript variable. 我将其传递给javascript变量。 But i don't know why the mac and status are blank, any help much appreciated. 但是我不知道为什么Mac和状态是空白,任何帮助都非常感谢。
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;
}
}
}
Do you have any limitation on any library? 您对任何图书馆都有限制吗? I mean are you using JSON library from http://org.json or which library? 我的意思是您使用的是http://org.json的 JSON库还是哪个库?
Following is the code that I've tried using JSON library from http://org.json : 以下是我尝试使用来自http://org.json的 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/ 您可以在此处阅读有关API的更多信息: http : //json.org/java/
JsonArray.fromObject -- Creates a JSONArray. JsonArray.fromObject-创建一个JSONArray Inspects the object type to call the correct JSONArray factory method. 检查对象类型以调用正确的JSONArray工厂方法。 Accepts JSON formatted strings, arrays and Collections . 接受JSON格式的字符串,数组和Collections 。
And Map which you are passing is not JSON formatted. 您要传递的地图不是JSON格式的。 So try using add() method on JsonArray Or put() method on JsonObject. 因此,请尝试在JsonArray上使用add()方法或在JsonObject上使用put()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.