001/*
002 *  Copyright (c) 2022-2025, 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.google.gson.Gson;
019import com.google.gson.reflect.TypeToken;
020
021/**
022 * @author michael
023 */
024public class GsonTypeHandler extends BaseJsonTypeHandler<Object> {
025
026    private static Gson gson;
027    private final Class<?> propertyType;
028    private Class<?> genericType;
029
030    public GsonTypeHandler(Class<?> propertyType) {
031        this.propertyType = propertyType;
032    }
033
034    public GsonTypeHandler(Class<?> propertyType, Class<?> genericType) {
035        this.propertyType = propertyType;
036        this.genericType = genericType;
037    }
038
039    @Override
040    protected Object parseJson(String json) {
041        if (genericType != null) {
042            TypeToken<?> typeToken = TypeToken.getParameterized(propertyType, genericType);
043            return getGson().fromJson(json, typeToken);
044        } else {
045            return getGson().fromJson(json, propertyType);
046        }
047    }
048
049    @Override
050    protected String toJson(Object object) {
051        return getGson().toJson(object);
052    }
053
054
055    public static Gson getGson() {
056        if (null == gson) {
057            gson = new Gson();
058        }
059        return gson;
060    }
061
062    public static void setGson(Gson gson) {
063        GsonTypeHandler.gson = gson;
064    }
065
066}