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