在javax.json中使用两个对象渲染JSON

时间:2019-01-08 04:41:34

标签: java java-ee javax.json

给出这两个带注释的类:

public class Clazz1 {
    @JsonbProperty("val11")
    String value11;
    @JsonbProperty("val12")
    String value12;
    .....
}


public class Clazz2 {
    @JsonbProperty("val21")
    String value21;
    @JsonbProperty("val22")
    String value22;
    .....
}

我需要生成一个包含两个对象的JSON,例如:

    Clazz1 c1 = new Clazz1();
    Clazz1 c2 = new Clazz2();
    c1.setValue1("ABC");
    ...  other settings

    JsonObject json = Json.createObjectBuilder()
             .add("c1", c1)
             .add("c2", c2)
             .build();

上面的add方法不接受对象,如何创建同时包含对象c1c2的JSON?

1 个答案:

答案 0 :(得分:1)

一种方法是使用JsonObjectBuilder API并手动构建对象:

JsonBuilderFactory factory = Json.createBuilderFactory();
    JsonObject value = factory.createObjectBuilder()
    .add("c1", factory.createObjectBuilder()
    .add("value11", c1.getValue11()))
    .add("c2", factory.createObjectBuilder()
    .add("value21", c1.getValue21()))

参考:https://docs.oracle.com/javaee/7/api/javax/json/JsonObjectBuilder.html

另一种方法是使用JsonbBuilder API:

JsonbConfig jsonbConfig = new JsonbConfig()
   .withPropertyNamingStrategy(
     PropertyNamingStrategy.LOWER_CASE_WITH_DASHES);
Map<String, Object> objectMap = new HashMap<>();
objectMap.put("c1", c1);
objectMap.put("c2", c2);
String json = JsonbBuilder.create(jsonbConfig).toJson(objectMap);

参考:https://www.ibm.com/developerworks/library/j-javaee8-json-binding-3/index.html