3

I tried several times, but I can not solve it and I need help.

I want JsonNode to Object

JsonNode :

{
    "usdusd" : 1.00,
    "usdkrw" : 1100
}

MyObject

public class MyObject {
    private BigDecimal usd;
    private BigDecimal krw;
}

How can I mapping using org.modelmapper.ModelMapper? JsonNode -> MyObject

bassseo
  • 181
  • 1
  • 8

3 Answers3

0

This is the implementation through objectmapper:

ObjectMapper mapper=new ObjectMapper();
MyObject value=mapper.readValue(jsonNode,MyObject.class);

This is the implementation through modelmapper

ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().addValueReader(new JsonElementValueReader());
JsonElement responseElement = new JsonParser().parse(json);
MyObject foo = mapper.map(responseElement, MyObject.class);
GauravRai1512
  • 834
  • 6
  • 14
0

I am using Spring Boot (2.4.2). Jackson is the default parser here, so no need of adding any dependency. I am using the following code to convert a JsonNode to My Object using ObjectMapper only (without the need of ModelMapper). Here jsonNode is an instance of com.fasterxml.jackson.databind.JsonNode:

import com.fasterxml.jackson.databind.ObjectMapper;

...

ObjectMapper mapper = new ObjectMapper();
MyObj myObj = mapper.treeToValue(jsonNode, MyObj.class);

Of course it will throw a checked exception called

com.fasterxml.jackson.core.JsonProcessingException

so you need to do "throws" or "try-catch" it mandatorily.

Mayank
  • 79
  • 6
0

use @JsonProperty("usdusd") on field usd, @JsonProperty("usdkrw") on field krw to map your filed to the json node. then use ObjectMapper as @Mayank said.

Pthahnil
  • 61
  • 3