de.elomagic.carafile.share.JsonUtil.java Source code

Java tutorial

Introduction

Here is the source code for de.elomagic.carafile.share.JsonUtil.java

Source

/* 
 * Copyright 2014 Carsten Rambow, elomagic.
 *
 * 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 de.elomagic.carafile.share;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 *
 */
public final class JsonUtil {

    private JsonUtil() {
    }

    /**
     * Creates a {@link Gson} instance inclduing (de)serializer for class {@link Date}.
     *
     * @return
     */
    public static Gson createGsonInstance() {
        GsonBuilder gb = new GsonBuilder();
        gb.registerTypeAdapter(Date.class, new DateDeserializer());
        gb.registerTypeAdapter(Date.class, new DateSerializer());
        return gb.create();
    }

    public static MetaData readFromReader(final Reader reader) {
        return read(reader, MetaData.class);
    }

    public static <T> T read(final Reader reader, Class<T> clazz) {
        Gson gson = createGsonInstance();
        return gson.fromJson(reader, clazz);
    }

    public static InputStream write(final Object o, final Charset charset) {
        Gson gson = createGsonInstance();
        String s = gson.toJson(o);

        return new ByteArrayInputStream(s.getBytes(charset));
    }

    public static void write(final Object o, final Writer writer) {
        Gson gson = createGsonInstance();
        gson.toJson(o, writer);
    }

    public static String write(final Object o) {
        Gson gson = createGsonInstance();
        return gson.toJson(o);
    }
}