@Test
public void demo1() throws IOException {
//文件-->String(方式一)
InputStream in = super.getClass().getClassLoader().getResourceAsStream("com/dmj/json/lab2/per.json");//相对路径
byte[] bs = new byte[10];//定义缓冲区,大小为1
int len = -1;
StringBuffer sb = new StringBuffer();//字符串拼接为sb(读取一个拼接一个)
while ((len = in.read(bs)) != -1){//不断向缓冲区读取内容,如果不等于-1,说明有内容
String str = new String(bs,0,len);//读取的字节数组转换字符串
sb.append(str);//进行拼接
}
//StringBuffer-->String
String s = sb.toString();
//String-->JSON
JSONObject json = new JSONObject(s);
System.out.println(json);
}
方式二:绝对路径读取
@Test
public void demo2() throws IOException {
//文件-->String(方式二,需要commons-io.jar包)
String s = FileUtils.readFileToString(
new File("D:\\javaSpace\\java_questions\\src\\com\\dmj\\json\\lab2\\per.json"),
"utf8");//绝对路径
//String-->JSON
JSONObject json = new JSONObject(s);
System.out.println(json);
}
运行结果
二、json对象解析json文件
创建Person对象,此处省略了有参/无参构造方法、get()方法、set()方法;
public class Person {
private String name;
private int age;
private Address address;
}
public class Address {
private String homeAddress;
private String schoolAddress;
}
map–>json
@Test
public void demo3() throws IOException {
//准备json数据(map-->json)
Map<String, Person> map = new HashMap<>();
Person p1 = new Person("zs",20,new Address("杭州","宁波"));
Person p2 = new Person("ls",21,new Address("台州","上海"));
Person p3 = new Person("ww",22,new Address("衢州","南京"));
map.put("zs",p1);
map.put("ls",p2);
map.put("ww",p3);
//map-->json
JSONObject json = new JSONObject(map);
//生成json文件
Writer w = new FileWriter("D:\\javaSpace\\java_questions\\src\\com\\dmj\\json\\lab2\\per1.json");
json.write(w);
w.close();
System.out.println("生成json文件成功!");
}