Java中json数据的常见转换

Map, JavaBean ,字符串 转化为JSON

 /*Map转化为json*/
    static public void test1() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name", "youyuan");
        JSONObject jsonObject = new JSONObject(hashMap);
        System.out.println(jsonObject);
    }

    /*javaBean转化为json*/
    static public void test2() {
        Person person = new Person("1", "zs", 22);
        JSONObject jsonObject = new JSONObject(person);
        System.out.println(jsonObject);
    }

    /*字符串转化为json*/
    static public void test3() {
        String json = "{\"name\":\"zs\",\"id\":\"1\",\"age\":22}";
        JSONObject jsonObject = new JSONObject(json);
        System.out.println(jsonObject);
    }

将文件转化成json

  /*将文件转化成json
    * 文件-->字符串
    * 字符串-->json
    * 方法一*/
    static void test4() throws IOException {
        FileInputStream inputStream = new FileInputStream("src/main/resources/person.json");
        byte[] bytes = new byte[1024];
        StringBuffer stringBuffer =new StringBuffer();
        int len =-1;
        while ((len = inputStream.read(bytes)) != -1){
            stringBuffer.append(new String(bytes),0,len);
        }
        JSONObject jsonObject = new JSONObject(stringBuffer.toString());
        System.out.println(jsonObject);
 }
 
    /** 方法二,使用类加载器*/
    void test5() throws IOException {
        InputStream inputStream =   super.getClass().getClassLoader().getResourceAsStream("person.json");
        byte[] bytes = new byte[1024];
        StringBuffer stringBuffer =new StringBuffer();
        int len =-1;
        while ((len = inputStream.read(bytes)) != -1){
            stringBuffer.append(new String(bytes),0,len);
        }
        JSONObject jsonObject = new JSONObject(stringBuffer.toString());
        System.out.println(jsonObject);
    }

直接使用工具类

//文件变字符串
 String s = FileUtils.readFileToString(new File("E:\\IDEA工程\\json\\json\\src\\main\\resources\\person.json"));
 System.out.println(s);

生成json文件

  /*生成json文件*/
    public void test6() throws IOException {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name", "youyuan");
        hashMap.put("id", UUID.randomUUID().toString());
        JSONObject jsonObject = new JSONObject(hashMap);
        //将数据写入到文件当中
        FileWriter writer = new FileWriter("G:\\json.txt");
        jsonObject.write(writer);
        writer.close();
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值