001/* 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.handler; 017 018import com.fasterxml.jackson.core.JsonProcessingException; 019import com.fasterxml.jackson.databind.JavaType; 020import com.fasterxml.jackson.databind.ObjectMapper; 021import com.mybatisflex.core.exception.FlexExceptions; 022 023import java.io.IOException; 024import java.util.Collection; 025 026/** 027 * @author michael 028 */ 029public class JacksonTypeHandler extends BaseJsonTypeHandler<Object> { 030 031 private static ObjectMapper objectMapper; 032 private final Class<?> propertyType; 033 private Class<?> genericType; 034 private JavaType javaType; 035 036 public JacksonTypeHandler(Class<?> propertyType) { 037 this.propertyType = propertyType; 038 } 039 040 public JacksonTypeHandler(Class<?> propertyType, Class<?> genericType) { 041 this.propertyType = propertyType; 042 this.genericType = genericType; 043 } 044 045 @Override 046 protected Object parseJson(String json) { 047 try { 048 if (genericType != null && Collection.class.isAssignableFrom(propertyType)) { 049 return getObjectMapper().readValue(json, getJavaType()); 050 } else { 051 return getObjectMapper().readValue(json, propertyType); 052 } 053 } catch (IOException e) { 054 throw FlexExceptions.wrap(e, "Can not parseJson by JacksonTypeHandler: " + json); 055 } 056 } 057 058 @Override 059 protected String toJson(Object object) { 060 try { 061 return getObjectMapper().writeValueAsString(object); 062 } catch (JsonProcessingException e) { 063 throw FlexExceptions.wrap(e, "Can not convert object to Json by JacksonTypeHandler: " + object); 064 } 065 } 066 067 068 public JavaType getJavaType() { 069 if (javaType == null){ 070 javaType = getObjectMapper().getTypeFactory().constructCollectionType((Class<? extends Collection>) propertyType, genericType); 071 } 072 return javaType; 073 } 074 075 public static ObjectMapper getObjectMapper() { 076 if (null == objectMapper) { 077 objectMapper = new ObjectMapper(); 078 } 079 return objectMapper; 080 } 081 082 public static void setObjectMapper(ObjectMapper objectMapper) { 083 JacksonTypeHandler.objectMapper = objectMapper; 084 } 085 086}