Java返回JSONArray [英] Java return JSONArray
问题描述
我正在尝试从java中的Map创建一个jsonarray。我将它传递给javascript变量。但我不知道为什么mac和状态是空白的,任何帮助都非常感激。
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.
我需要什么:
[{"12345":{"mac":"FFFFFFFF", "status":"ON"}]
我使用当前代码获得的信息:
What i am getting with my current code:
[{"12345":{}]
这是我的代码,
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;
}
}
}
推荐答案
您对任何库有任何限制吗?我的意思是您使用的是 http://org.json,JSON库中的JSON库或哪个库?
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 :
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());
}
}
您可以阅读有关API的更多信息这里:
http://json.org/java/
You can read more about the API here: http://json.org/java/
这篇关于Java返回JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!