封装类与json的转换的工具类JsonUtils

使用了Google 的Gson类进行了封装。
大家在使用的时候别忘了导入下载google-gson-x.x.x-jar 包

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
 * JsonUtils  
 * 能将封装类或者封装类的集合转为JSON 
 * 能将JSON解析成封装类 或者封装类的集合
 * @author shaoduo
 */
public class JsonUtils {
    /**
     * 针对于bean 或者 List<bean>来说将这个 封装对象转为json字符串
     * @param obj
     * @return String
     */
    public static <T> String pubOrPubsToJson(T t)
    {   
        Gson gson = new Gson();
        String jsonStr=gson.toJson(t);
        return jsonStr;
    }

    /**
     * 判断是否数据需要解析成JsonStr
     * @param retJsonStr
     * @return boolean
     */
    public static boolean isNeedFromJsonToPub(String retJsonStr)
    {
        if(retJsonStr.length()>100)
        {
            return true;
            //System.out.println("是否需要解析::"+);
        }
        return false;
    }

    /**
     * 解析从服务器端返回的字符串转为pub封装类型
     * @param retJsonStr 
     * @param obj
     */     

     public static <T> T jsonToPub(String jsonString, Class<T> cls) {
            T t = null;
            try {
                Gson gson = new Gson();
                t = gson.fromJson(jsonString, cls);
            } catch (Exception e) {
                // TODO: handle exception
            }
            return t;
        }
        /**
         * 解析从服务器端返回的字符串转为pubList封装类型
         * @param retJsonStr 
         * @param obj
         */     

    public static <T> List<T> jsonToPubs(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson() ;
           list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
            }.getType());

        //  list=(List<T>)JSONObject.toBean(jsonString,cls);
        } catch (Exception e) {
        }
        return list;
    }

    /**
     * 解析从服务器端返回的字符串转为pubList封装类型
     * @param retJsonStr 
     * @param obj
     */     
    public static <T> List<T> JsonToPubs(String json, Class<T[]> type) {
        T[] list = new Gson().fromJson(json, type);
        return Arrays.asList(list);
    }

}

如何使用
1. 将集合List 的 PeoplePubList 转为Json

String peopleListJsonStr=JsonUtils.pubOrPubsToJson(PeoplePubList);

2. 将封装类 People 的 people 转为Json

String peJsonStr= JsonUtils.pubOrPubsToJson(people);

3. peopleListJsonStr的json数组解析为 PeopleList

PeopleList = JsonUtils.JsonToPubs(getJson, People[].class) ;

或者

PeopleList = JsonUtils.jsonToPubs(getJson, People[].class) ;

4.将PeopleStr的json数组解析为People

people=jsonToPub(PeopleStr) ;

版权声明
author :shaoduo
原文来自:http://blog.youkuaiyun.com/shaoduo
其他出处均为转载,原创作品,欢迎读者批评指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值