com.ab.util.JsonUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.ab.util.JsonUtil.java

Source

/*
 * Copyright (C) 2012 www.amsoft.cn
 * 
 * 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 com.ab.util;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

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

// TODO: Auto-generated Javadoc

/**
 *  2012 amsoft.cn 
 * ??StrUtil.java 
 * ??json?.
 *
 * @author 
 * @version v1.0
 * @date2013-01-17 ?11:52:13
 * @param <T>
 */
public class JsonUtil {

    private static GsonBuilder gsonBuilder = new GsonBuilder();

    /**
     * 
     * ??json.
     * @param list
     * @return
     */
    public static String toJson(Object src) {
        String json = null;
        try {
            Gson gson = gsonBuilder.create();
            json = gson.toJson(src);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 
     * ??json.
     * @param list
     * @return
     */
    public static String toJson(List<?> list) {
        String json = null;
        try {
            Gson gson = gsonBuilder.create();
            json = gson.toJson(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 
     * ??json.
     * @param json
     * @param typeToken new TypeToken<ArrayList<?>>() {};
     * @return
     */
    public static <T> T fromJson(String json, TypeToken<T> typeToken) {
        List<?> list = null;
        try {
            Gson gson = gsonBuilder.create();
            Type type = typeToken.getType();
            list = gson.fromJson(json, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) list;
    }

    /**
     * 
     * ??json.
     * @param json
     * @param clazz
     * @return
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        Object obj = null;
        try {
            Gson gson = gsonBuilder.create();
            obj = gson.fromJson(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) obj;
    }

    public static void setGsonBuilderDateFormat(String format) {
        gsonBuilder.setDateFormat(format);
    }

}