Gson解析json字符串,并封装成List<T>

最近一个项目中,需要将从服务器上获取到的JSON字符串转换为对象,大概研究了一下,发现在项目中很多地方都要用到,而且有的时候需要返回的是一个集合,所以写了个方法,留着自用。
public class JsonUtils {
    /**
     * 将传入的json字符串按类模板解析成对象
     * @param json 需要解析的json字符串
     * @param cls 类模板
     * @return 解析好的对象
     */
    public static <T> T getObj(String json,Class<T> cls){
        Gson gson = new Gson();
        T bean = (T) gson.fromJson(json, cls);
        return bean;
    }
    /**
     * 将传入的对象解析成json字符串
     * @param bean 需要解析的对象
     * @return 解析完成的json字符串
     */
    public static <T> String getJsonString(T bean){
        Gson gson = new Gson();
        String json = gson.toJson(bean, bean.getClass());
        return json;
    }
    /**
     * 将获取到的json字符串转换为对象集合进行返回
     * @param jsonData 需要解析的json字符串
     * @param cls 类模板
     * @return
     */
    public <T> List<T> getObjList(String jsonData,Class<T> cls){
        List<T> list = new ArrayList<T>();
        if (jsonData.startsWith("[") && jsonData.endsWith("]")) {//当字符串以“[”开始,以“]”结束时,表示该字符串解析出来为集合
            //截取字符串,去除中括号
            jsonData = jsonData.substring(1, jsonData.length() -1);
            //将字符串以"},"分解成数组
            String[] strArr = jsonData.split("\\},");
            //分解后的字符串数组的长度
            int strArrLength = strArr.length;
            //遍历数组,进行解析,将字符串解析成对象
            for (int i = 0; i < strArrLength; i++) {
                String newJsonString = null;
                if (i == strArrLength -1) {
                    newJsonString = strArr[i];
                } else {
                    newJsonString = strArr[i] + "}";
                }
                T bean = getObj(newJsonString, cls);
                list.add(bean);
            }
        }
        if (list == null || list.size() == 0) {
            return null;
        }
        return list;
    }
}
这里测试一下,JSON字符串有点长,就放在后面了。
public class Test {
    public static void main(String[] args) {

        Exposure exp = JsonUtils.getObj(json, Exposure.class);
        System.out.println("exp = " + exp);

        String myJson = JsonUtils.getJsonString(exp);
        System.out.println("myJson = " + myJson);

        List<User> userList = JsonUtils.getObjList(listJson, User.class);
        for (User user : userList) {
            System.out.println("user = " + user);
        }
    }
}

public static String json = "{\"Id\": 9928,\"CustomerId\": 9248,\"Remark\": \"大类其他\",\"ExposureItem\": {\"Id\": 20734,\"Has\": true,\"AllergyNames\": null,\"AllergyNamesStr\": \"化学品,毒物,射线,其他\",\"Other\": \"暴露史其他\",\"PropertyName\": \"ExposureItem\",\"Text1\": null,\"Text2\": null,\"Text3\": null,\"Text4\": null,\"Text5\": null,\"Text6\": null,\"Text7\": null,\"Text8\": null,\"Text9\": null,\"Text10\": null,\"Text11\": null,\"Text12\": null,\"Text13\": null,\"Text14\": null,\"Date\": null,\"Remark\": null},\"OccupationalItem\": {\"Id\": 20735,\"Has\": true,\"AllergyNames\": null,\"AllergyNamesStr\": null,\"Other\": null,\"PropertyName\": \"OccupationalItem\",\"Text1\": \"工种\",\"Text2\": null,\"Text3\": \"毒物种类\",\"Text4\": \"1997\",\"Text5\": \"1\",\"Text6\": \"2\",\"Text7\": \"1998\",\"Text8\": \"3\",\"Text9\": \"4\",\"Text10\": null,\"Text11\": null,\"Text12\": null,\"Text13\": null,\"Text14\": null,\"Date\": null,\"Remark\": null}}";

    public static String listJson = "[{\"UserId\":9555,\"Name\":\"测试账号\",\"UserType\":\"user\",\"TypeName\":\"VIP金卡\",\"UserTypeId\":4,\"Sex\":0,\"IDCard\":\"110102198506020034\",\"Country\":\"中国\",\"WorkUnit\":\"四川\",\"Phone\":\"02887654321\",\"Mobile\":\"13901234567\",\"QQ\":\"412455414\",\"Mail\":\"412455414@qq.com\",\"FamilyContact1\":\"张三\",\"FamilyContact2\":\"李四\",\"FamilyContact1Phone\":\"12345678912\",\"FamilyContact2Phone\":\"98765432121\",\"Address\":\"成都市\",\"NearbyHospital\":\"未知\",\"HealthServiceCentre\":\"没有\",\"ResidentType\":2,\"BloodType\":3,\"RHNegative\":2,\"EducationBackground\":5,\"Career\":1,\"Career_Other\":\"\",\"MaritalStatus\":0,\"MedicalPayWayId\":2,\"MedicalPayWay_Other\":\"\",\"SocialSecurityNo\":null,\"CardNo\":\"\",\"Birthday\":\"1985-06-02T00:00:00+08:00\",\"ServiceBuyWayId\":1,\"ServiceBuyWay_Other\":null,\"ExpireTime\":\"2016-03-17T00:00:00+08:00\",\"Height\":\"\",\"Waistline\":\"\",\"Hipline\":\"\",\"Weight\":\"\"},{\"UserId\":9555,\"Name\":\"测试账号\",\"UserType\":\"user\",\"TypeName\":\"VIP金卡\",\"UserTypeId\":4,\"Sex\":0,\"IDCard\":\"110102198506020034\",\"Country\":\"中国\",\"WorkUnit\":\"四川\",\"Phone\":\"02887654321\",\"Mobile\":\"13901234567\",\"QQ\":\"412455414\",\"Mail\":\"412455414@qq.com\",\"FamilyContact1\":\"张三\",\"FamilyContact2\":\"李四\",\"FamilyContact1Phone\":\"12345678912\",\"FamilyContact2Phone\":\"98765432121\",\"Address\":\"成都市\",\"NearbyHospital\":\"未知\",\"HealthServiceCentre\":\"没有\",\"ResidentType\":2,\"BloodType\":3,\"RHNegative\":2,\"EducationBackground\":5,\"Career\":1,\"Career_Other\":\"\",\"MaritalStatus\":0,\"MedicalPayWayId\":2,\"MedicalPayWay_Other\":\"\",\"SocialSecurityNo\":null,\"CardNo\":\"\",\"Birthday\":\"1985-06-02T00:00:00+08:00\",\"ServiceBuyWayId\":1,\"ServiceBuyWay_Other\":null,\"ExpireTime\":\"2016-03-17T00:00:00+08:00\",\"Height\":\"\",\"Waistline\":\"\",\"Hipline\":\"\",\"Weight\":\"\"},{\"UserId\":9555,\"Name\":\"测试账号\",\"UserType\":\"user\",\"TypeName\":\"VIP金卡\",\"UserTypeId\":4,\"Sex\":0,\"IDCard\":\"110102198506020034\",\"Country\":\"中国\",\"WorkUnit\":\"四川\",\"Phone\":\"02887654321\",\"Mobile\":\"13901234567\",\"QQ\":\"412455414\",\"Mail\":\"412455414@qq.com\",\"FamilyContact1\":\"张三\",\"FamilyContact2\":\"李四\",\"FamilyContact1Phone\":\"12345678912\",\"FamilyContact2Phone\":\"98765432121\",\"Address\":\"成都市\",\"NearbyHospital\":\"未知\",\"HealthServiceCentre\":\"没有\",\"ResidentType\":2,\"BloodType\":3,\"RHNegative\":2,\"EducationBackground\":5,\"Career\":1,\"Career_Other\":\"\",\"MaritalStatus\":0,\"MedicalPayWayId\":2,\"MedicalPayWay_Other\":\"\",\"SocialSecurityNo\":null,\"CardNo\":\"\",\"Birthday\":\"1985-06-02T00:00:00+08:00\",\"ServiceBuyWayId\":1,\"ServiceBuyWay_Other\":null,\"ExpireTime\":\"2016-03-17T00:00:00+08:00\",\"Height\":\"\",\"Waistline\":\"\",\"Hipline\":\"\",\"Weight\":\"\"}]";
如有不对的地方,请指教。如有侵权,请指出。
交流群:181745436
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值