JSON数据和Java
对象的相互转换
Java对象转为JSON
①导入jar包
在编程环境中导入JSON解析器的相关jar包,这里以jackson为例进行讲解。比如:
import com.fasterxml.jackson.databind.ObjectMapper;
②创建核心对象
比如创建Jackson核心对象ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
③调用相关方法进行转换
writeValueAsString(obj):将obj对象转为json字符串,这是最常用的方法,比如:
//1.创建Person对象Person p = new Person();p.setName("张三");p.setAge(23);p.setGender("男");p.setBirthday(new Date());//2.创建Jackson核心对象ObjectMapper mapper = new ObjectMapper();//3.转换String json = mapper.writeValueAsString(p);//4.查看输出结果System.out.println(json);
输出结果如下所示:
{"name":"张三","age":23,"gender":"男"}
当obj对象为List集合时,输出的结果如下所示:
[{"name":"张三","age":23,"gender":"男"}]
当obj对象为Map对象时,比如:
//1.创建map对象Map<String,Object> map = new HashMap<String,Object>();map.put("name","张三");map.put("age",23);map.put("gender","男");//2.创建Jackson核心对象ObjectMapper mapper = new ObjectMapper();//3.转换String json = mapper.writeValueAsString(map);//4.查看输出结果System.out.println(json);
输出的结果如下所示:
{"gender":"男","name":"张三","age":23}
writeValue(参数1,obj):根据参数的不同,输出不同的结果,参数的选择如下:
File:将obj对象转换为JSON字符串,并保存到指定的文件中。
Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中。
OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中。
比如:
//1.创建Person对象Person p = new Person();p.setName("张三");p.setAge(23);p.setGender("男");p.setBirthday(new Date());//2.创建Jackson核心对象ObjectMapper mapper = new ObjectMapper();//3.转换到指定的文件中mapper.writeValue(new File("d://a.txt"),p);
④注解
@JsonIgnore:排除属性。在转换时忽略该键值对,比如:
@JsonIgnore // 忽略该属性private Date birthday;
@JsonFormat:属性值得格式化,将该键值对中的值格式化,比如:
@JsonFormat(pattern = "yyyy-MM-dd")private Date birthday;
转换结果为:
"birthday":"2018-07-07"
JSON转为Java对象
将JSON转为Java对象的步骤与上面一致,只是转换方法不同,一般采用下面的方法进行转换:
readValue(json字符串数据, Class)
比如:
//1.初始化JSON字符串String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":23}";//2.创建ObjectMapper对象ObjectMapper mapper = new ObjectMapper();//3.转换为Java对象Person person = mapper.readValue(json, Person.class);//4.查看输出结果System.out.println(person);