将JSONObject添加到JSONArray java
问题描述:
我需要添加一个对象到JSONArray
(它已经包含元素),所以我必须知道要添加的属性的类型,如果这是一个整数或字符串等等,.. 如何使用java将该对象添加到我的数组中?将JSONObject添加到JSONArray java
答
正如其他人所建议的,您可以简单地使用JsonArray构建器中的add方法。
import javax.json.*;
public class JsonExample {
public static void main(String[] args) {
JsonObject personObject = Json.createObjectBuilder()
.add("name", Json.createObjectBuilder()
.add("given", "John")
.add("middle", "Edward")
.add("surname", "Doe")
.build())
.add("age", 42)
.add("isMarried", true)
.add("address", Json.createObjectBuilder()
.add("street", "Main Street")
.add("city", "New York")
.add("zipCode", "10044")
.add("country", "United States")
.build())
.add("phoneNumber", Json.createArrayBuilder()
.add("+1 (718) 111-1111")
.add("+1 (718) 111-1112")
.build())
.build();
JsonArray personArray = Json.createArrayBuilder()
.add(personObject) // Add person to array.
.build();
System.out.println(JsonUtil.prettyPrint(personArray));
}
}
这只是用来格式化JSON输出。
import java.io.StringWriter;
import java.util.*;
import javax.json.*;
import javax.json.stream.JsonGenerator;
/* Based on: http://*.com/a/32500882/1762224 */
public class JsonUtil {
public static String prettyPrint(JsonStructure json) {
return jsonFormat(json, JsonGenerator.PRETTY_PRINTING);
}
public static String jsonFormat(JsonStructure json, String... options) {
StringWriter stringWriter = new StringWriter();
Map<String, Boolean> config = buildConfig(options);
JsonWriterFactory writerFactory = Json.createWriterFactory(config);
JsonWriter jsonWriter = writerFactory.createWriter(stringWriter);
jsonWriter.write(json);
jsonWriter.close();
return stringWriter.toString();
}
private static Map<String, Boolean> buildConfig(String... options) {
Map<String, Boolean> config = new HashMap<String, Boolean>();
if (options != null) {
for (String option : options) {
config.put(option, true);
}
}
return config;
}
}
本例使用以下相关:
apply plugin: 'java'
repositories {
jcenter()
}
dependencies {
compile 'javax.json:javax.json-api:1.1.0-M1'
compile 'org.glassfish:javax.json:1.1.0-M1'
}
这里是输出:
[
{
"name": {
"given": "John",
"middle": "Edward",
"surname": "Doe"
},
"age": 42,
"isMarried": true,
"address": {
"street": "Main Street",
"city": "New York",
"zipCode": "10044",
"country": "United States"
},
"phoneNumber": [
"+1 (718) 111-1111",
"+1 (718) 111-1112"
]
}
]
'jsonArray.add(JSONObject的);' – Mistalis
,其JSON API您使用?杰克逊或戈森或任何? – Darshit
在java中了解关于json api的更多信息http://docs.oracle.com/javaee/7/api/javax/json/package-summary.html – xFighter