Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中使用map创建JSONArray_Java_Json_Hashmap - Fatal编程技术网

如何在java中使用map创建JSONArray

如何在java中使用map创建JSONArray,java,json,hashmap,Java,Json,Hashmap,下面的代码将使用JSONArray创建嵌套的JSON对象 public static void main(String[] args) { JSONArray array=new JSONArray(); JSONObject jsonObject=new JSONObject(); JSONObject jsonObject1=new JSONObject(); JSONObject jsonObject2=new JSONObj

下面的代码将使用
JSONArray
创建嵌套的
JSON
对象

public static void main(String[] args) {
        JSONArray array=new JSONArray();
        JSONObject jsonObject=new JSONObject();
        JSONObject jsonObject1=new JSONObject();
        JSONObject jsonObject2=new JSONObject();
        jsonObject2.put("testapp", true);
        array.put(jsonObject2);
        jsonObject1.put("test", array);
        jsonObject1.put("test2", false);
        jsonObject1.put("app", 1);
        jsonObject.put("MAINs", jsonObject1);
        System.out.println(jsonObject);
    }
输出为:

{"MAINs":{"app":1,"test2":false,"test":[{"testapp":true}]}}

但我想用java创建上述JSON对象的映射表示,就像我使用JSONObject和JSONArray创建的一样。

您可以使用org.JSON库中的toMap方法,该方法将JSONObject转换为映射对象

public static void main(String[] args) {
    JSONArray array=new JSONArray();
    JSONObject jsonObject=new JSONObject();
    JSONObject jsonObject1=new JSONObject();
    JSONObject jsonObject2=new JSONObject();
    jsonObject2.put("testapp", true);
    array.put(jsonObject2);
    jsonObject1.put("test", array);
    jsonObject1.put("test2", false);
    jsonObject1.put("app", 1);
    jsonObject.put("MAINs", jsonObject1);
    System.out.println(jsonObject);
     Map<String, Object> map=jsonObject.toMap();
     System.out.println(map);
}
publicstaticvoidmain(字符串[]args){
JSONArray数组=新的JSONArray();
JSONObject JSONObject=新的JSONObject();
JSONObject JSONObject 1=新的JSONObject();
JSONObject JSONObject 2=新的JSONObject();
jsonObject2.put(“testapp”,true);
put(jsonObject2);
jsonObject1.put(“测试”,数组);
jsonObject1.put(“test2”,false);
jsonObject1.put(“app”,1);
jsonObject.put(“主电源”,jsonObject 1);
System.out.println(jsonObject);
Map Map=jsonObject.toMap();
系统输出打印项次(map);
}

您可以使用Gson库。您可以使用它的toJson方法,它将反序列化您作为输入参数发送的任何对象。