在编写代码时,经常会碰到一些类型转化的需求,比如对象转JSON或者对象转Map等等,如果自己手写又太麻烦,因此我总结了一下JSON、对象和Map三者之间的转化关系,如下图
- 调用如图的方法需要导入所需依赖,如下:
com.alibaba fastjson 1.2.76
- 以下是测试代码
public class TestMapObject {
@Data
public static class Student {
private String name;
private int age;
}
public static void main(String[] args) {
//对象<====>JSON<====>Map
Student student = new Student();
student.setName("张三");
student.setAge(1);
//对象->json
String json = JSONObject.toJSONString(student);
System.out.println("对象->json = " + json);
//json->map
Map map = JSONObject.parseObject(json);
System.out.println("json->map = " + map);
//map-->json
String json1 = JSONObject.toJSONString(map);
System.out.println("map-->json = " + json1);
//json-->对象
Student student2 = JSONObject.parseObject(json1, Student.class);
System.out.println("json-->对象 = " + student2);
}
}
- 控制台打印结果如下:
对象->json = {“age”:1,“name”:“张三”}
json->map = {“name”:“张三”,“age”:1}
map–>json = {“name”:“张三”,“age”:1}
json–>对象 = TestMapObject.Student(name=张三, age=1)
- 此外,在进行java对象转JSON时,可以设置当前类的部分属性不参与转化
@JsonInclude(JsonInclude.Include.NON_NULL)
//类注解:当前类中若属性为null,则不参与JSON转化
@JsonProperty("created_at")
//属性注解:设置返回JSON串的名字
@JSONIgnore
//属性注解:设置不参与JSON转换



