[英]How to create JSONArray using map in java
I have the below code which will create nested JSON
Object with JSONArray
.我有下面的代码,它将使用
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);
}
Output is:输出是:
{"MAINs":{"app":1,"test2":false,"test":[{"testapp":true}]}}
But I wanted to create the map representation of the above JSON object in java like how I have created using JSONObject and JSONArray.但是我想在 java 中创建上述 JSON 对象的地图表示,就像我如何使用 JSONObject 和 JSONArray 创建一样。
You can use toMap method present in org.json library which will convert JSONObject to Map object.您可以使用 org.json 库中的 toMap 方法将 JSONObject 转换为 Map 对象。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.