Solve some problems encountered by ObjectMapper. convertValue of

  • 2021-10-13 07:40:24
  • OfStack

Source code:


public <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef) throws IllegalArgumentException { return (T) _convert(fromValue, _typeFactory.constructType(toValueTypeRef)); }

This method is used to convert bean to map with jackson

Examples:


List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });

Objects obtained from other services in micro-services will report errors if they are strongly changed from Object to custom types, so ObjectMapper conversion is used.


ObjectMapper mapper = new ObjectMapper();
DefaultResponse defaultResponse = proxy.getData();
List<Resource> resources = (<Resource>) defaultResponse.getData();  // The scene here is: data Yes 1 A Object Type, but it is actually 1 A List<Resouce> , want to put List Convert each object in to a usable object 
for (int i = 0; i < serviceDateResources.size(); i++) {
    Resource resource = mapper.convertValue(resources.get(i), Resource.class);   // After this process, resource It is the available type. If you don't convert it, you will report an error 
}

Some properties are set to null during conversion, so there is no need to convert

Treatment method:

Add the following annotations to the entity class quotient to be converted


@JsonInclude(Include.NON_NULL) 
@JsonInclude(Include.Include.ALWAYS)  Default  
@JsonInclude(Include.NON_DEFAULT)  Property is not serialized to the default value  
@JsonInclude(Include.NON_EMPTY)  Property is   Empty ("")   Or for  NULL  Neither is serialized  
@JsonInclude(Include.NON_NULL)  Property is NULL  Non-serialization  

jackson objectMapper json String, Object bean, map, Array list Conversion Common Methods List:


ObjectMapper mapper = new ObjectMapper();

1. Object to json string


User user=new User();
String userJson=mapper.writeValueAsString(user);

2. Map to json string


Map map=new HashMap();  
String json=mapper.writeValueAsString(map);

3. Array list to json string


Student[] stuArr = {student1, student3};  
String jsonfromArr =  mapper.writeValueAsString(stuArr);

4. json string to object


String expected = "{\"name\":\"Test\"}";
User user = mapper.readValue(expected, User.class);

5. json string to Map


String expected = "{\"name\":\"Test\"}";
Map userMap = mapper.readValue(expected, Map.class);

6. json string to object array List


List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });
0

7. json string to Map array List < Map < String,Object > >


List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });
1

8. jackson converts objects to LinkedHashMap by default:


List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });
2

9. Method of interconversion between json string and list or map


ObjectMapper objectMapper = new ObjectMapper();
 // Encounter date Convert according to this format 
 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 objectMapper.setDateFormat(fmt);
 
  String preference = "{name:' Hou Yong '}";
        //json String conversion map
  Map<String, String> preferenceMap = new HashMap<String, String>();
  preferenceMap = objectMapper.readValue(preference, preferenceMap.getClass());
  
  //map Turn json String 
  String result=objectMapper.writeValueAsString(preferenceMap);

10. Conversion of bean to map


List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });
4

Error reported by objectMapper. convertValue ()

The error message is as follows:

com. fasterxml. jackson. databind. exc. InvalidDefinitionException: Cannot construct instance java. time: cannot deserialize from Object value (no delegate-or property-based Creator) at [Source: UNKNOWN; line:-1, column:-1] (through reference chain: net. too1.tplus. user. user. entity. User ["createTime"])

According to the above error report, it is the cause of java. time. LocalDateTime type. ObjectMapper cannot serialize LocalDateTime. Add the following annotations to solve it


List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });
5

List<SObject> sObjects = new ObjectMapper().convertValue(map.get("list"), new TypeReference<List<SObject>>() { });
6

Related articles: