java jsonarray添加,将JSONObject添加到JSONArray java

I need to add an object to a JSONArray(which contains elements already), so I have to know the type of the attribute to add, if this is an integer or a string etc,..

How to add that object to my array with java?

解决方案

As others have suggested, you can simply use the add method in the JsonArray builder.

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));

}

}

This is simply used to format the JSON output.

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 config = buildConfig(options);

JsonWriterFactory writerFactory = Json.createWriterFactory(config);

JsonWriter jsonWriter = writerFactory.createWriter(stringWriter);

jsonWriter.write(json);

jsonWriter.close();

return stringWriter.toString();

}

private static Map buildConfig(String... options) {

Map config = new HashMap();

if (options != null) {

for (String option : options) {

config.put(option, true);

}

}

return config;

}

}

This example uses the following dependencies:

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'

}

Here is the output:

[

{

"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"

]

}

]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值