1

I need to create a JSON response with some dynamic fields in java. Here is an example of the JSON response I want to return :

{
    "success": true,
    "completed_at": 1400515821,
    "<uuid>": {
        type: "my_type",
        ...
    }, 
    "<uuid>": {
        type: "my_type",
        ...
    }
}

The "success" and the "completed_at" fields are easy to format. How can I format the fields? What would be the corresponding java object?

Basically I want to work with 2 java objects :

public class ApiResponseDTO {

    private boolean success;
    private DateTime completedAt;

    ...
}

and

public class AuthenticateResponseDTO extends ApiResponseDTO {

    public List<ApplianceResponseDTO> uuids = new     ArrayList<ApplianceResponseDTO>();

}

These java objects don't correspond to the expected JSON format. It would work if I could change the JSON format to have a list, but I can't change it.

Thanks a lot!

  • Will the JSON value mapped to `` always be the same? – Sotirios Delimanolis Feb 17 '15 at 17:25
  • And will the dynamic keys always be named ``? JSON has undefined behavior for duplicate keys. – Sotirios Delimanolis Feb 17 '15 at 17:26
  • If you could wrap this similair parts into separate object you could store it as Map: http://stackoverflow.com/questions/28548380/gson-fromjson-to-java-class-structure-where-property-names-are-not-known – Pshemo Feb 17 '15 at 17:26
  • Instead of , I will have values like "ae12-54ef-dfd...", so I won't have duplicate keys. The inner json will always be the same (type, updated date ...). I've seen this answer @Pshemo, but in this example the map is named "details". In my case, I won't have a named map. The solution might be really easy but I can't see it... – Guillaume Lambert Feb 18 '15 at 12:53
  • Are you able to change structure of this JSON? If so just wrap your set of `"completed_at":1400515821, "uuid1":{data1}, "uuid2":{data2}` into something like `"completed_at":1400515821, "details":{"uuid1":{data1},"uuid2":{data2}}` and now you can use Map without problems. – Pshemo Feb 18 '15 at 15:13
  • It would be much easier but unfortunately I can't... – Guillaume Lambert Feb 19 '15 at 10:58

1 Answers1

0

You can massage your data into JSON form using the javax.json library, specifically the JsonObjectBuilder and the JsonArrayBuilder. You'll probably want to nest a few levels of a toJson() method which will either give you the string representation you're looking for, or the JsonObject/JsonArray you desire. Something like this:

JsonArray value = null;
JsonArrayBuilder builder = Json.createArrayBuilder();
for (ApplianceResponseDTO apr : uuids) {
    builder.add(apr.toJson());
}
value = builder.build();
return value;
Foosh
  • 1,195
  • 12
  • 16