JavaBean 与 JSON 的相互转换(基于 Gson 的封装)

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

import java.io.*;
import java.lang.reflect.Type;

public class JsonUtils {

    private static Gson gson = null;

    // 初始化
    static {
        // 设置 json 规格化打印使 javaBean 转换为字符串后文本内容更易读
        gson = new GsonBuilder().setPrettyPrinting().create();
    }

    /**
     * 读取 json 文件的内容
     *
     * @param path json 文件的路径
     * @return json 文件的内功
     */
    public static String readJson(String path) {
        String json = null;
        String buffer = null;
        StringBuilder content = new StringBuilder();

        try (FileReader fr = new FileReader(path);
             BufferedReader buffReader = new BufferedReader(fr)) {
            while ((buffer = buffReader.readLine()) != null)
                content.append(buffer);
            json = content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(".json 文件读取异常");
        }

        return json;
    }

    /**
     * 向 json 文件中写入 json 数据
     *
     * @param path    json 文件的路径
     * @param content 要写入的数据内同
     * @return 是否写入成功
     */
    public static boolean writeJson(String path, String content) {
        boolean flag = false;
        try (FileWriter fw = new FileWriter(path);
             BufferedWriter buffWriter = new BufferedWriter(fw)) {
            buffWriter.write(content);
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(".json 文件的写入异常");
        }
        return flag;
    }

    /**
     * 将 json 文件中的数据转换为 java bean 对象
     *
     * @param path json 文件的路径
     * @param type 要转换的 java bean 对象的 Class 对象
     * @param <T>  java bean 对象的数据类型
     * @return java bean 对象
     */
    public static <T> T json2Bean(String path, Class<T> type) {
        final String json = readJson(path);
        return gson.fromJson(json, type);
    }

    /**
     * 将 java bean 对象写入到 json 文件中并保存
     *
     * @param path json 文件的路径
     * @param bean java bean 对象
     * @param <T>  java bean 对象的数据类型
     */
    public static <T> void bean2Json(String path, T bean) {
        final String json = gson.toJson(bean);
        if (writeJson(path, json))
            System.out.println("Json 写入成功");
        else
            System.out.println("Json 写入失败");
    }

    /**
     * 将 json 转换为 List Map 等集合对象
     * @param path json 文件的路径
     * @param type 集合的类型:集合名<元素名>
     * @param <T> 集合的类型
     * @return 经转换后的集合
     */
    public static <T> T json2coll(String path, Type type) {
        final String json = readJson(path);
        return gson.fromJson(json, type);
    }

    /**
     * 将集合转换为 json 数据格式
     * @param path json 文件的路径
     * @param coll 集合
     * @param <T> 集合的数据类型
     */
    public static <T> void coll2Json(String path, T coll) {
        bean2Json(path, coll);
    }

}

测试使用:

@Test
    public void jsonTest() throws FileNotFoundException {

        final Person p1 = new Person("1", "zhang", 20);
        final Person p2 = new Person("2", "wang", 20);
        final Person p3 = new Person("3", "li", 20);
        final Person p4 = new Person("4", "zhao", 20);

        final ArrayList<Person> people = new ArrayList<>();
        people.add(p1);
        people.add(p2);
        people.add(p3);
        people.add(p4);
        String path = "test.json";

        final Person person = JsonUtils.json2Bean(path, Person.class);
        System.out.println(person); // Person{id='1', name='zhang', age=20}

        //JsonUtils.coll2Json(path, people);
        final Type type = new TypeToken<ArrayList<Person>>() {
        }.getType();
        final ArrayList arrayList = JsonUtils.json2coll(path, type);
        System.out.println(arrayList);
    }

json 文件的内容:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值