标签:com strong oid color end pack new test sys
1、pom.xml文件添加依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
2、将对象转为json格式的字符串
注意:JSONobject.toJSONString(object xx) 将对象转为json格式的字符串,其依赖于toString()方法,并且toString()方法的展示格式有固定的要求,就是lombok.Data中@Data
重写的类toString()方法的格式,具体如何手动书写toString()方法,待后续研究。。
错误代码:
package com.testdemo; import com.alibaba.fastjson.JSONObject; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; public class FastJson1 { public static void main(String[] args) { Teacher t2 =new Teacher(20,"李四"); //将对象转为json字符串 System.out.println(JSONObject.toJSONString(t2)); } } @AllArgsConstructor @NoArgsConstructor class Teacher{ //年龄+姓名 int age; String name; } ===结果=== {}
正确代码:
通过@Data注解实现对类的toString()方法的重写
public class FastJson1 { public static void main(String[] args) { Teacher t2 =new Teacher(20,"李四"); System.out.println(JSONObject.toJSONString(t2)); } } @Data @AllArgsConstructor @NoArgsConstructor class Teacher{ //年龄+姓名 int age; String name; } ==结果=== {"age":20,"name":"李四"}
标签:com strong oid color end pack new test sys
原文地址:https://www.cnblogs.com/jesse-zhao/p/14806138.html