一、依赖包
<!--json包--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.15</version></dependency>
二、举例
1.实体对象转Json字符串
1.1 代码实现
Dog.java:
package com.xj.entity;/*** @Author: xjfu* @Create: 2024/03/29 15:58* @Description: 狗实体类*/
public class Dog {//姓名private String name;//品种private String kind;//年龄private Integer age;public String getKind() {return kind;}public void setKind(String kind) {this.kind = kind;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}
FastJsonUtil.java:
package com.xj.util;import com.alibaba.fastjson.JSON;
import com.xj.entity.Dog;/*** @Author: xjfu* @Create: 2024/03/29 16:03* @Description: 基于com.alibaba.fastjson的工具类*/
public class FastJsonUtil {public static void main(String[] args) {System.out.println("将实体转成json字符串:" + entityToString());}/*** 将实体类转成json字符串* @return*/public static String entityToString(){Dog dog = new Dog();dog.setName("小白");dog.setKind("中华田园犬");dog.setAge(19);//将dog转成Json字符串return JSON.toJSONString(dog);}
}