4

I have a map that unsure it keys,but I am sure the keys contains all the pojo fields, says:

public class MyPojo{ 
    String name,
    String addr
}
//map contains keys that not in MyPojo field,e.g. age
map = {"name":"john","addr":"sf school","age":"21"}

In Java how can I can convert it to pojo MyPojo instance? the following method throw exception:

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
WesleyHsiung
  • 351
  • 2
  • 13

2 Answers2

8

You can use @JsonIgnoreProrperties by Jackson in your MyPojo class. The exception is cause of ObjectMapper not being able to find exact mapping in your MyPojo class.

The API is provided in the same library, that of ObjectMapper.

So here is what your class should look like:

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyPojo{
   String name;
   String addr;
   //Other variables
}

To import it in your code, you need to add the following:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

I hope this solves your problem and thisis exactly what you're looking for.

Safeer Ansari
  • 772
  • 4
  • 13
1

As you are working on generics keys(previously unknown), there might be chances of keys(attribute names) present in the map as a key doesn't present in POJO as an attribute. So, set below properties to false, when you create an ObjectMapper instance, so that any unknown or missing attributes wouldn't throw any exceptions.

        final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
        mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Prasanth Rajendran
  • 4,570
  • 2
  • 42
  • 59