如何在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方法,它将反序列化您作为输入参数发送的任何对象。