jackson - ObjectMapper 정리 [계속..]

Posted on 2021. 7. 23. 10:44
Filed Under Programming/Java

배경: jackson 1.9 이하 버전에서 필요해짐.

출처: 직렬화&역직렬화


public class Coordinates {
    byte red;

    @JsonProperty("r")
    public byte getR() {
      return red;
    }

    @JsonProperty("red")
    public void setRed(byte red) {
      this.red = red;
    }
}
///////
Coordinates obj = new Coordinates();
obj.setRed((byte) 5);

ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(obj));

Coordinates r = mapper.readValue("{\"red\":25}",Coordinates.class);
System.out.println("Deserialization: " + r.getR());

///////결과:
Serialization: {"r":5}
Deserialization: 25


public static Map<String, Object> objectToMap(Object obj) {
	ObjectMapper objectMapper = new ObjectMapper();
//	objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
//	objectMapper.configure(Feature.AUTO_DETECT_FIELDS, true);
	
    // value=null일때 처리
	objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
		@Override
		public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
			jgen.writeString("");
		}
	});
	
    // key=null일때 처리
	objectMapper.getSerializerProvider().setNullKeySerializer(new JsonSerializer<Object>() {
		  @Override
		  public void serialize(Object value, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
			  jgen.writeFieldName("null");
		  }
	});
	
	@SuppressWarnings("unchecked")
	Map<String, Object> map = objectMapper.convertValue(obj, Map.class);
	return map;
}


 

반응형

About

by 쑤기c

반응형