文章目录

  • jar包下载
  • json对象写入到json文件
  • 读取json文件成json对象
  • 更多例子


jar包下载

使用这个jar包:https:///stleary/JSON-java 然后下载这个jar包操作读写文件更方便:https://commons.apache.org/proper/commons-io/

java读写json文件 java 读取json文件_java

json对象写入到json文件

package com.item1.hello;

import .FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

public class test1 {

    // 测试json对象写入到文件
    public static void testJsonWriteFile() throws IOException {
        JSONArray ja = new JSONArray(); //json列表

        JSONObject jo = new JSONObject(); //json字典
        jo.put("filename", "test");
        jo.put("value1", 123);
        jo.put("value2", 12.34);
        jo.put("value2", true);

        ja.put(jo);  //字典推入列表


        File file = new File("json1.json");
        FileUtils.write(file, ja.toString(), "utf-8", false);
    }

    public static void main(String[] args) throws IOException {

        testJsonWriteFile();
    }
}

读取json文件成json对象

package com.item1.hello;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;


import .FileUtils;


public class test1 {

    public static void testJsonReadFile() throws IOException {
        File file=new File("json1.json");
        String content= FileUtils.readFileToString(file,"UTF-8");
        System.out.println(content);
        JSONArray ja=new JSONArray(content);
        System.out.println(ja);

    }

    public static void main(String[] args) throws IOException {
        testJsonReadFile();
    }
}

更多例子

https:///stleary/JSON-java/blob/master/