简体   繁体   中英

Render JSON with two objects in javax.json

Given these two annotated classes :

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


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

What I need is to generate a JSON that includes two objects, for example:

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

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

The add method above doesn't accept objects, how to create a JSON that includes both objects c1 and c2 ?

One approach is to use the JsonObjectBuilder API and build the object manually:

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

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

The other is to use the 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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM