LemonMan
LemonMan

Reputation: 3143

Add labels to JSON with Jackson

I have a Map<String,Integer>

that I want in the following form [{text: String, count: Integer},{text: String2, count: Integer2},...]

I know how to do this stuff with comprehensions in python but never used Jackson before for java, which I need to sue now.

I've done this to convert the map to Json

ObjectMapper mapper = new ObjectMapper();
try {
    System.out.println(mapper.writeValueAsString(myMap));
    //(looks like {"word":1,"word2":2,"word3":5}) (so I need to add a label text:
    // before each word a label weight before each number and put each word/number
    // block in a separate {})
    } catch (JsonGenerationException e) {
    e.printStackTrace();
    } catch (JsonMappingException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

Upvotes: 0

Views: 541

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38655

Algorithm is simple:

  1. Create POJO class with two properties: text and count.
  2. Convert Map<String, Integer> into List of POJO instances.
  3. Convert result List into JSON

Upvotes: 2

Related Questions