[JAVA] Mapping json to an already instantiated Object

To a bean class that cannot use the default constructor with no arguments It can be used when mapping Json.

Source


import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectMapper2 extends ObjectMapper{
	public <T> T readValue(String content, T bean)
		        throws IOException, JsonParseException, JsonMappingException
	{
		// JSON -> Map
		Map<String,String> map = null;
		ObjectMapper mapper = new ObjectMapper();
		try {
			map = mapper.readValue(content, new TypeReference<LinkedHashMap<String,String>>(){});
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.forEach( (key,value)->{
			try{
				org.apache.commons.lang3.reflect.FieldUtils.writeDeclaredField(bean, key, value, true);
			}catch(Exception e){
				e.printStackTrace();
			}
		});
		return bean;
	}

}

Caller

AbcBean bean = objectMapper.readValue(loginSessionJson, new AbcBean(null,null,null));

Recommended Posts

Mapping json to an already instantiated Object
Convert ruby object to JSON format
How to store an object in PostgreSQL as JSON with MyBatis (Mapper XML)
JAVA object mapping library
19 Corresponds to object creation
How to pass an object to Mapper in MyBatis without arguments
Mapping to a class with a value object in How to MyBatis
What is an immutable object? [Explanation of how to make]