Java教程

Java中json文件与json对象之间的转换

本文主要是介绍Java中json文件与json对象之间的转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java中json文件与json对象之间的转换

  • 一、json文件解析json对象
    • per.json文件内容
    • 方式一:相对路径读取
    • 方式二:绝对路径读取
    • 运行结果
  • 二、json对象解析json文件
    • 运行结果

一、json文件解析json对象

per.json文件内容

{
  "name" : "zhangsan",
  "age" : 23,
  "address" :
  {
    "homeAddress" : "杭州",
    "schoolAddress" : "上海"
  }
}

方式一:相对路径读取

@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文件成功!");
}

运行结果

  • 生成per1.json文件内容
{
  "ww":{"address":{"schoolAddress":"南京","homeAddress":"衢州"},"name":"ww","age":22},
  "zs":{"address":{"schoolAddress":"宁波","homeAddress":"杭州"},"name":"zs","age":20},
  "ls":{"address":{"schoolAddress":"上海","homeAddress":"台州"},"name":"ls","age":21}
}
这篇关于Java中json文件与json对象之间的转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!