All Downloads are FREE. Search and download functionalities are using the official Maven repository.

acscommons.io.jsonwebtoken.gson.io.GsonDeserializer Maven / Gradle / Ivy

There is a newer version: 6.6.0
Show newest version
/*
 * Copyright (C) 2014 jsonwebtoken.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package acscommons.io.jsonwebtoken.gson.io;

import com.google.gson.Gson;
import acscommons.io.jsonwebtoken.io.DeserializationException;
import acscommons.io.jsonwebtoken.io.Deserializer;
import acscommons.io.jsonwebtoken.lang.Assert;
import acscommons.io.jsonwebtoken.lang.Strings;

import java.io.IOException;

public class GsonDeserializer implements Deserializer {

    private final Class returnType;
    private final Gson gson;

    @SuppressWarnings("unused") //used via reflection by RuntimeClasspathDeserializerLocator
    public GsonDeserializer() {
        this(GsonSerializer.DEFAULT_GSON);
    }

    @SuppressWarnings({"unchecked", "WeakerAccess", "unused"}) // for end-users providing a custom gson
    public GsonDeserializer(Gson gson) {
        this(gson, (Class) Object.class);
    }

    private GsonDeserializer(Gson gson, Class returnType) {
        Assert.notNull(gson, "gson cannot be null.");
        Assert.notNull(returnType, "Return type cannot be null.");
        this.gson = gson;
        this.returnType = returnType;
    }

    @Override
    public T deserialize(byte[] bytes) throws DeserializationException {
        try {
            return readValue(bytes);
        } catch (IOException e) {
            String msg = "Unable to deserialize bytes into a " + returnType.getName() + " instance: " + e.getMessage();
            throw new DeserializationException(msg, e);
        }
    }

    protected T readValue(byte[] bytes) throws IOException {
        return gson.fromJson(new String(bytes, Strings.UTF_8), returnType);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy