środa, 23 września 2015

Generic JSON SerDe with Jackson2

import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

static class SerDe<T> {
 
 public static <T>  String serialize(T obj) throws JsonProcessingException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, As.PROPERTY);
  return mapper.writeValueAsString(obj);
 }
 
 public static <T> T deserialize(String s, Class<T> clazz) throws JsonProcessingException, IOException {
  ObjectMapper mapper = new ObjectMapper();
  mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, As.PROPERTY);
  return mapper.readerFor(clazz).readValue(s);
 }

}

Brak komentarzy:

Prześlij komentarz