GsonDiskConverter.java 1.87 KB
Newer Older
konghaorui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
package com.ydl.ydlnet.cache.diskconverter;

import com.ydl.ydlnet.cache.utils.RxCacheLogUtils;
import com.ydl.ydlnet.cache.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;

/**
 * Created by Chu on 2017/2/28.
 */

public class GsonDiskConverter implements IDiskConverter {

    private Gson mGson = new Gson();


    public GsonDiskConverter() {
        this(new Gson());
    }

    public GsonDiskConverter(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.mGson = gson;
    }


    @Override
    public <T> T load(InputStream source, Type type) {

        T value = null;
        try {
            TypeAdapter<?> adapter = mGson.getAdapter(TypeToken.get(type));
            JsonReader jsonReader = mGson.newJsonReader(new InputStreamReader(source));
            value = (T) adapter.read(jsonReader);
        } catch (JsonIOException | JsonSyntaxException e) {
            RxCacheLogUtils.log(e);
        } catch (IOException e) {
            RxCacheLogUtils.log(e);
        } finally {
            Utils.close(source);
        }
        return value;
    }

    @Override
    public boolean writer(OutputStream sink, Object data) {
        try {

            String json = mGson.toJson(data);
            byte[] bytes = json.getBytes();
            sink.write(bytes, 0, bytes.length);
            sink.flush();
            return true;
        } catch (JsonIOException | IOException e) {
            RxCacheLogUtils.log(e);
        } finally {
            Utils.close(sink);
        }
        return false;
    }
}