Jackson converting Map<CustomEntity, Integer> to JSON creates toString() from CustomEntity

StackOverflow https://stackoverflow.com/questions/23659531

  •  22-07-2023
  •  | 
  •  

Вопрос

I have custom Entity that i want to put as Json to my view page

But when i serialize it in map using ObjectMapper from Jackson i receive String created from toString() method

@Test
public void test() throws JsonProcessingException {
    Map<ProductEntity, Integer> map = new HashMap<ProductEntity, Integer>();

    ProductEntity prod = new ProductEntity();
    prod.setIdProduct(1);

    map.put(prod, 1);

    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(map));
}

Received: {"com.onlineshop.entity.ProductEntity@2":1} where "com.onlineshop.entity.ProductEntity@2" is a String, not an object.

So how can i make it to be an Object?

I need exactly Map, not another type of Collection

Это было полезно?

Решение 2

Thanks to all for your answers. I solved it by creating new DTO which contains :

private ProductEntity 
private Integer

fields.

Другие советы

You either need to annotate your ProductEntity object so Jackson knows how to serialize it or use a Mix In annotation if you are not able to modify the ProductEntity class. IIRC there are also global Jackson options you can set that tell it how to handle POJOs.

Since you didn't specify which version of Jackson you're using I can't link to the correct documents but there is a ton of information available on the Jackson sites on how to use annotations and mix ins.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top