Vivek Dhiman
Vivek Dhiman

Reputation: 1995

ObjectMapper readValue Type Convert From LinkedHasMap to Custom Type

I have a statement below which gives me list of Objects which are of Type LinkedHashMap.

List<MyCustomClassA> optionsList = mapper.readValue(mapper.writeValueAsString(OtherClassA.getItems()), List.class);

MyCustomClassA

@Data
@Builder
public class MyCustomClassA {
    private Boolean disabled;
    private Boolean selected;
    private String text;
    private String value;
}

But the value that optionsList iterate are the type of LinkedHashMap. OtherClassA.getItems() returns the List<MyCustomClassB>

MyCustomClassB

public class MyCustomClassB {
    private String text;
    private String value;
    Private List<Images> imageList;
}

What I am looking to achieve to get optionsList which should be of type MyCustomClassA.

Upvotes: 4

Views: 1439

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40068

Because you are not providing the exact TypeReference that json string need to be deserialized. Since you provided raw type list List.class objectmapper treats it as List<Object>. And you are deserializing JsonArray of JsonObject, so ObjectMapper converts into List<LinkedHashMap> because JsonObject represents and implements Map

List<MyCustomClassA> optionsList = objectMapper.readValue(mapper.writeValueAsString(OtherClassA.getItems()), new TypeReference<List<MyCustomClassA>>(){});

And also you need to add @NoArgConstructor and @AllArgConstructor annotation on MyCustomClassA because lombok @Data will only bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor

Upvotes: 3

Related Questions