[英]Add JSONObject to JSONArray java
我需要將一個對象添加到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://stackoverflow.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"
]
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.