2017-11-03 8 views
1

내 웹 사이트에서 액세스를 관리하는 권한 클래스가있는 엔티티 클래스 (계정)가 있습니다. 내 때문에, JSON으로 매핑되지문자열을 db to java 클래스로 매핑

{"permissionOne" : true, "permissionTwo" : false} 

필드 :

사실
@Column(length = 300) 
private String permissions; 

는,이 분야가 같은 예를 들어, JSON 문자열을 포함 : 그것은 다음과 같은 내 DB에 문자열로 매핑 된 것 db는 JSON 유형을 지원하지 않는 이전 버전의 MySql이며 버전을 변경할 수 없습니다.

public class JsonHelper { 

    /** Singleton parser instance */ 
    private static ObjectMapper parser = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) 
      .enable(Feature.ALLOW_UNQUOTED_FIELD_NAMES, Feature.ALLOW_UNQUOTED_CONTROL_CHARS); 

    /** Logger instance */ 
    private static Logger LOG = LoggerFactory.getLogger(JsonHelper.class); 

    /** 
    * converts one java object into json {@link String}g 
    * 
    * @param toConvert 
    * @return converted {@link String} object 
    */ 
    public static String toJsonString(Object toConvert) { 

     String result = null; 
     try { 
      result = parser.writeValueAsString(toConvert); 
     } 
     catch (JsonProcessingException e) { 
      LOG.error("Cannot parse value : " + toConvert + " StackTrace : ", e); 

     } 

     return result; 
    } 

    /** 
    * Converts one json {@link String} into java object 
    * 
    * @param toConvert json string to convert 
    * @param convertType class type to be converted into 
    * @return converted java object 
    */ 
    public static <T> T fromJsonString(String toConvert, Class<T> convertType) { 

     if (toConvert == null) return null; 

     T result = null; 

     try { 
      result = parser.readValue(toConvert, convertType); 
     } 
     catch (IOException e) { 
      LOG.error("Cannot parse value : " + convertType + " " + toConvert + " StackTrace : ", e); 

     } 

     return result; 
    } 

    /** 
    * Converts one java object to {@link JsonNode} 
    * 
    * @param toConvert object to convert 
    * @return converted json object 
    */ 
    public static JsonNode toJsonNode(Object toConvert) { 

     return parser.valueToTree(toConvert); 

    } 

    /** 
    * Converts one {@link JsonNode} into java object 
    * 
    * @param toConvert to be converted 
    * @param convertType type of class to convert to 
    * @return converted java object 
    */ 
    public static <T> T fromJsonNode(JsonNode toConvert, Class<T> convertType) { 

     T result = null; 

     try { 
      result = parser.treeToValue(toConvert, convertType); 
     } 
     catch (JsonProcessingException e) { 
      LOG.error("Cannot parse value : " + convertType + " " + toConvert + 
    " StackTrace : ", e); 
     } 

     return result; 

    } 

    /** 
    * Converts one json into list of objects 
    * 
    * @param toConvert json to convert 
    * @param convertType list type 
    * @return converted liist with objects 
    */ 
    public static <T> List<T> fromJsonNodeList(JsonNode toConvert, Class<T> 
    convertType) { 

     List<T> result = new ArrayList<>(); 
     if (!toConvert.isArray()) return result; 

     for (JsonNode node : toConvert) { 
      result.add(fromJsonNode(node, convertType)); 
     } 

     return result; 
    } 

    public static ObjectMapper getParser() { 
     return parser; 
    } 

} 

가 나는 할 때 :

Permission permission = JsonHelper.fromJsonString(account.getPermissions(), Permission.class); 

허가 변수가 null

나는 또한 JsonHelper 클래스가 있습니다.

이유를 모르겠습니다. 그것은 모두 좋은 것 같습니다. 내가 빠진 것이 있습니까?

다른 방식으로 사용해도 되나요? 덕분에 ! 나는이 코드 조각에서 보는 것과 판단

답변

0

:이 방법은 경우에만 toConvertnull를 반환 할 수 있습니다

public static <T> T fromJsonString(String toConvert, Class<T> convertType) { 

    if (toConvert == null) return null; 

    T result = null; 

    try { 
     result = parser.readValue(toConvert, convertType); 
    } 
    catch (IOException e) { 
     LOG.error("Cannot parse value : " + convertType + " " + toConvert + " StackTrace : ", e); 

    } 

    return result; 
} 

null 또는 파서는 값을 읽을 수 없습니다.

toConvertnull 인 경우 허용됩니다 (permissions 필드가 실제로 선택 사항이라고 가정). toConvert 매개 변수가 null이라는 경고를 기록해야합니다. 그 외에도 Java 8의 Optional을 반환 값으로 사용할 수 있습니다.

다른 경우에는 데이터베이스에 가비지 (읽을 수없는 JSON)가있을 수 있으며 로깅과 별도로 정리 작업이 필요합니다. 지속적으로 오류를 일으킬 수있는 데이터를 저장소에 저장하지 않도록하십시오.

+0

toConvert는 null이 아닙니다. DB에서 문자열은 유효한 JSON입니다. { "accessAllVisits": true, "accessAllDocuments": false} – Gjord83

+0

@ Gjord83 : 그러면 로그에 메시지가 표시됩니다. –

+0

로그에 아무것도 표시되지 않습니다 .... getPermissions (obv)를 수행 할 때 쿼리 만 – Gjord83