[英]How to create JsonArray and JsonObject in JsonObject java
How to create JsonArray and JsonObject in JsonObject 如何在JsonObject中创建JsonArray和JsonObject
{
"users": [7, 16, 35],
"group_id": "askskdjejs139d.."
}
Thank for your help :) 谢谢您帮忙 :)
You can try the following code: 您可以尝试以下代码:
JSONObject user1 = new JSONObject();
try {
user1.put("user_id", "7");
user1.put("group_id", "askskdjejs139d");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject user2 = new JSONObject();
try {
user2.put("user_id", "16");
user2.put("group_id", "askskdjejs139d");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(user1);
jsonArray.put(user2);
JSONObject userObj = new JSONObject();
userObj.put("Users", jsonArray);
String jsonStr = userObj.toString();
System.out.println("jsonString: "+jsonStr);
You can do this using org.json
Library. 您可以使用
org.json
库执行此操作。
// Creating a json object
JSONObject jsonObj = new JSONObject();
// Adding elements to json object
jsonObj.put("key", "value"); // the value can also be a json object or a json array
// Creating a json object from an existing json string
JSONObject jsonObj = new JSONObject("Your json string");
// Creating a json array
JsonArray jsonArray = new JsonArray();
// Adding a json object to json object to json Array
jsonArray.add(jsonObj);
// Adding json array as an element of json object
jsonObject.put("key", "<jsonArray>");
You can call toString()
method of JsonObject
or JsonArray
to get the String
representation of the json object/array. 您可以调用
JsonObject
或JsonArray
toString()
方法来获取json对象/数组的String
表示形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.