Skip to content
Advertisement

Serialise Java Map as [{key: “key1, value: ”value1“}, {key: ”key2, value: “value2”}, …] [closed]

I’m going around in circles here because there’s about 50 questions on Stack Overflow asking how to get the default jackson behaviour… I don’t want that behaviour so don’t tell me this question has already been answered. Thanks.

I have a simple map HashMap<String, String> and need to serialise it into a form that a 3rd party app understands. I need the following:

[
  {
    "key": "k1",
    "value": "v1"
  },
  {
    "key": "k2",
    "value": "v2"
  },
  ...
]

I do NOT want this: {k1: "v1", k2: "v2", ...}

Anyone who understands the black art of jackson care to share their wisdom?

Advertisement

Answer

static class Wrapper {
    String key, value;

    public Wrapper(String key, String value) {
        this.key = key;
        this.value = value;
    }
}

public static void main(String[] args) throws Exception {

    Map<String, String> map = Map.of("key1", "value1", "key2", "value2");

    String json = new Gson().toJson(map.entrySet().stream()
            .map(e -> new Wrapper(e.getKey(), e.getValue()))
            .collect(Collectors.toSet()));

    System.out.println(json);
}

Output is:

[{"key":"key1","value":"value1"},{"key":"key2","value":"value2"}]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement