3

I have a Map which contains another Map as follows:

private ObjectMapper mapper;
private Map<String,Map<String,Long>> indicatorsList;

How can I use Jackson in order to convert it to POJO?

This is what I was trying to do:

public Map<String,Map<String,Long>> calculateIndicators(List<indicatorsDAO> events){

        Map<String,Map<String,Long>> indicatorsCountersMap=
            events.stream().collect(
                Collectors.groupingBy(
                    indicatorsDAO::getType,
                    Collectors.groupingBy(
                        indicatorsDAO::getLight,
                        Collectors.counting())
                )
            );

       return mapper.convertValue(indicatorsCountersMap,Indicators.class);

    }

This is Indicators class:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Indicators{
    private Map<String,Map<String,Long>> indicatorsList;
}

The results of this conversion is: null

This is how the map should look like, just an example:

    "indicatorsList": {
        "Bulb": {
          "Green": 2,
          "Red": 3
        },
        "Led": {
          "Red": 1
        }
}
  • You have to add fields in your Indicators class like `String main; Map second value`; – Dred Apr 10 '19 at 06:03
  • Jackson serializes objects to JSON, and deserializes JSON to objects. You have an object, and want to transform it into another object. No JSON involved. Why would you use Jackson? Don't you just need `new Indicators(indicatorsCountersMap)`? – JB Nizet Apr 10 '19 at 06:07

1 Answers1

3

Try to use the below code snippet to convert your MAP object the JSON string.

ObjectMapper mapperObj = new ObjectMapper();
String jsonStr = StringUtils.EMPTY;

try {
    jsonStr = mapperObj.writeValueAsString(<<MAP OBJECT>>);
}
 catch (IOException e) { 
 e.printStackTrace();
}
Ravi
  • 192
  • 1
  • 7