重写toString方法 打印对象为json
程序员文章站
2022-03-26 16:52:11
...
1 需要引入alibaba的jar包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
2 代码示例
注意:写在对应的pojo类中
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
@Override
public String toString() {
return JSON.toJSONString(this, new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.UseISO8601DateFormat });
}
3 使用
直接使用被重写过的pojo类 即可得到json字符串
上一篇: Java 使用POI生成word
推荐阅读