Facebook
From nln, 1 Month ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 149
  1. import com.fasterxml.jackson.core.JsonProcessingException;
  2. import com.fasterxml.jackson.core.type.TypeReference;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.fasterxml.jackson.databind.SerializationFeature;
  5. import lombok.extern.slf4j.Slf4j;
  6.  
  7. import java.text.SimpleDateFormat;
  8. import java.util.List;
  9. import java.util.stream.Collectors;
  10.  
  11. @Slf4j
  12. public class JsonUtil {
  13.     private JsonUtil() {
  14.     }
  15.  
  16.     public static String objToString(Object prm) {
  17.         var mapper = new ObjectMapper();
  18.         mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
  19.         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  20.         mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
  21.         try {
  22.             return mapper.writeValueAsString(prm);
  23.         } catch (JsonProcessingException e) {
  24.             log.error("Parsing error. ", e);
  25.         }
  26.         return "";
  27.     }
  28.  
  29.     public static String toJson(Object obj) {
  30.         try {
  31.             return new ObjectMapper().writeValueAsString(obj);
  32.         } catch (JsonProcessingException e) {
  33.             throw new RuntimeException(e);
  34.         }
  35.     }
  36.  
  37.     public static <T> T fromJson(String json, Class<T> returnType) {
  38.         try {
  39.             return new ObjectMapper().readValue(json, returnType);
  40.         } catch (JsonProcessingException e) {
  41.             throw new RuntimeException(e);
  42.         }
  43.     }
  44.  
  45.     public static <T> T fromJson(String json, TypeReference<T> valueTypeRef) {
  46.         try {
  47.             return new ObjectMapper().readValue(json, valueTypeRef);
  48.         } catch (JsonProcessingException e) {
  49.             throw new RuntimeException(e);
  50.         }
  51.     }
  52.  
  53.     public static <T> T fromJsonElseNull(String json, TypeReference<T> valueTypeRef) {
  54.         try {
  55.             return new ObjectMapper().readValue(json, valueTypeRef);
  56.         } catch (JsonProcessingException e) {
  57.             log.error("Parsing error. ", e);
  58.             return null;
  59.         }
  60.     }
  61.  
  62.     public static String wrapWithQuotesAndJoin(List<String> strings) {
  63.         return strings.stream()
  64.                 .map(s -> "'" + s + "'")
  65.                 .collect(Collectors.joining(", "));
  66.     }
  67. }
  68.