1.java对象转换为json字符串
package com.chichung.json; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JavaToJson { public static void main(String[] args) throws JsonProcessingException { PersonBean p = new PersonBean(); p.setName("chichung"); p.setGender("男"); p.setAge(23); ObjectMapper om = new ObjectMapper(); String s = om.writeValueAsString(p); System.out.println(s); } }
输出结果:
{"name":"chichung","age":23,"gender":"男"}
- 还有另外一种转换方法:
writeValue(参数1,obj):
参数1:
File:将obj对象转换为JSON字符串,并保存到指定的文件中
Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
2.Json字符串转换为Java对象
package com.chichung.json; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class JavaToJson { public static void main(String[] args) throws IOException { String jsonStr = "{"name":"chichung","age":23,"gender":"男"}"; ObjectMapper om = new ObjectMapper(); PersonBean personBean = om.readValue(jsonStr, PersonBean.class); System.out.println(personBean); } }
---恢复内容结束---
---恢复内容结束---