1

Let's say I have the following Java enum:

@AllArgsConstructor
public enum Code {
    Code1("Short text 1", "Long text 1"),
    Code2("Short text 2", "Long text 2");

    private final String shorttext;
    private final String longtext;
}

Then System.out.println(JsonbBuilder.create().toJson(Code.Code1)) will result in ""Code1". I would like to have the following result:

{
  "shorttext": "Short text 1",
  "longtext": "Long text 1"
}

Is there a comfortable way to achive this? Maybe any Annotation I can use? Or is it mandatory to implement a custom Adapter?

By the way: org.json.JSONObject results in the desired format by default.

StSch
  • 377
  • 1
  • 4
  • 12

2 Answers2

1

I'm not really familiar with JSON-B, but it seems you'll need to write a serializer as described here: http://json-b.net/docs/user-guide.html#serializersdeserializers

It will probably be similar to the Customer example given. Something like:

public static class CodeSerializer implements JsonbSerializer<Code> {
    @Override
    public void serialize(Code code, JsonGenerator generator, SerializationContext ctx) {
        generator.writeStartObject();
        generator.write("shorttext", code.getShorttext());
        generator.write("longtext", code.getLongtext());
        generator.writeEnd();
    }
}
RoToRa
  • 37,635
  • 12
  • 69
  • 105
-1

You can do it with Map, like this:

Map<String, String> textMap = new HashMap<>();
textMap.put("longtext", Code.Code1.getLongtext());
textMap.put("shorttext", Code.Code1.getShorttext());
System.out.println(JsonbBuilder.create().toJson(textMap));

Output: {"longtext":"Long text 1","shorttext":"Short text 1"}

Also you will need to add @Getter to your Code enum

Baaarbz
  • 1
  • 2