javajacksonobjectmapper

Jackson Custom Object Mapper


I'm looking for some help. I have a requirement to convert the input json to a java object.

Input JSON is something like this

{
   "code" : "some code",
   "type" : "type1",
   "agents" : {
     "118023" : "testname1",
     "124244" : "testname2"
   }
   
}

I need to convert this to below java objects

class Top {
  private String code;
  private String type;
  private List<Agent> agents;
  //setters & getters
}

class Agent {
  private String code;
  private String name;
  //getters & setters
}

The Agent class field code should hold the key of the inner json object, while the name field should hold the value.

How can I achieve it? Do I really need a custom object mapper for this? Please help, thanks in advance.

Note: We should use object mapper only, no option to eliminate it as per the guidelines.


Solution

  • As @Chaosfire has already written in the comments, there is no configuration on the ObjectMapper that can convert the properties in the JSON agents object into a List of Agent instances.

    In this scenario, you're better off defining a custom deserializer, and mapping the agents node into a List<Agent>.

    Here is an implementation of your custom deserializer:

    public class MyListAgentsDeserializer extends StdDeserializer<List<Agent>> {
        public MyListAgentsDeserializer() {
            this(null);
        }
    
        public MyListAgentsDeserializer(Class<?> vc) {
            super(vc);
        }
    
        @Override
        public List<Agent> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
            JsonNode node = p.getCodec().readTree(p);
            return StreamSupport.stream(Spliterators.spliteratorUnknownSize(node.fields(), Spliterator.ORDERED), false).
                    map(n -> new Agent(n.getKey(), n.getValue().asText()))
                    .collect(Collectors.toList());
        }
    }
    

    Here is also a full example on OneCompiler.