dmz73
dmz73

Reputation: 1608

ModelMapper: how to map this json to Java?

I am attempting to use ModelMapper to map the following json as explained here http://modelmapper.org/user-manual/gson-integration/ but I am getting a NullPointerException and I can't figure what is wrong. Any tips please?

{"a": "aaa", "b": [{"c": "ccc"}]}   

public class Foo {
  private String a;
  private ArrayList<Bar> b;
}



public class Bar {
  private String c;
}

ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().addValueReader(new JsonElementValueReader());
JsonElement responseElement = new JsonParser().parse(json);
Foo foo = mapper.map(responseElement, Foo.class);

Upvotes: 0

Views: 7936

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

After review of what you meant and your comment in the question, this is very likely a bug in their implementation. The javadoc for ValueReader claims

Returns all member names for the source object, else null if the source has no members.

However, the only code that uses this method, PropertyInfoSetResolver#resolveAccessors(...), does not check for the existence of null. Member names in JSON only make sense for objects, but, here, you have a JSON array. That's why it fails.

As far as I can tell, the code doesn't check for null nor for source types that don't have members. I consider this a bug. The error is easily reproducible from the sample example by replacing any of the fields (and the corresponding JSON) with array types. You might want to contact the developer or change libraries.

Upvotes: 1

Related Questions