001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (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 io.jboot.components.serializer;
017
018import com.alibaba.fastjson.JSON;
019import com.alibaba.fastjson.parser.ParserConfig;
020import com.alibaba.fastjson.serializer.SerializerFeature;
021import com.alibaba.fastjson.util.IOUtils;
022import com.jfinal.log.Log;
023
024
025public class FastJsonSerializer implements JbootSerializer {
026
027    private static final Log LOG = Log.getLog(FastJsonSerializer.class);
028
029    private final static ParserConfig autoTypeSupportConfig = new ParserConfig();
030    static {
031        autoTypeSupportConfig.setAutoTypeSupport(true);
032    }
033
034    @Override
035    public byte[] serialize(Object obj) {
036        if (obj == null) {
037            return null;
038        }
039
040        return JSON.toJSONBytes(obj
041                , SerializerFeature.WriteClassName
042                , SerializerFeature.SkipTransientField
043                , SerializerFeature.IgnoreErrorGetter
044//                , SerializerFeature.IgnoreNonFieldGetter
045        );
046    }
047
048    @Override
049    public Object deserialize(byte[] bytes) {
050        if (bytes == null || bytes.length == 0) {
051            return null;
052        }
053
054        try {
055//            return JSON.parse(bytes, Feature.SupportAutoType);
056            return JSON.parse(new String(bytes, IOUtils.UTF8), autoTypeSupportConfig);
057        } catch (Exception e) {
058            LOG.error(e.toString(), e);
059        }
060
061        return null;
062    }
063
064
065}