引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
代码块:
@Test
void jsonTransformer() throws JSONException {
Guest guest = new Guest();
guest.setId(12);
guest.setUserName("小明");
guest.setUserPassword("123456");
//对象转json字符串
String s = JSON.toJSONString(guest);
System.out.println("对象转json字符串: "+s);
//json字符串转Java对象
Guest guest1 = JSON.parseObject(s, Guest.class);
System.out.println("json字符串转Java对象: "+guest1+guest1.getUserName());
//parse是json对象
Object parse = JSON.parse(s);
System.out.println("parse===="+parse.getClass());
//JSON对象转Java对象
Guest guest2 = JSON.toJavaObject((JSON) parse, Guest.class);
System.out.println("JSON对象转Java对象: "+guest2);
//JAVA对象转JSON对象
Object json = JSON.toJSON(guest2);
System.out.println("JAVA对象转JSON对象: "+json.getClass()+"\t"+json);
}
运行结果: