【问题标题】:Java return JSONArrayJava 返回 JSONArray
【发布时间】:2013-07-19 10:27:06
【问题描述】:

我正在尝试从 java 中的 Map 创建一个 jsonarray。我将它传递给一个 javascript 变量。但我不知道为什么 mac 和 status 是空白的,非常感谢任何帮助。

我需要什么:

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

我现在的代码得到了什么:

[{"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;
    }
  }
}

【问题讨论】:

    标签: java json


    【解决方案1】:

    您对任何库有任何限制吗?我的意思是您使用的是来自 http://org.json 的 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());
    
        }
    }
    

    您可以在此处阅读有关 API 的更多信息: http://json.org/java/

    【讨论】:

      【解决方案2】:

      JsonArray.fromObject-- 创建一个 JSONArray。 检查对象类型以调用正确的 JSONArray 工厂方法。 接受 JSON 格式的字符串、数组和集合

      您传递的 Map 不是 JSON 格式的。所以尝试在 JsonArray 上使用 add() 方法或在 JsonObject 上使用 put() 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多