实体类
package com.star.json;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Course {
// @JSonField(name = "COURSENAME")
private String COURSENAME;
}
package com.star.json;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student {
// @JSonField(name = "NAME")
private String NAME;
// @JSonField(name = "AGE")
private int AGE;
// @JSonField(name = "COURSE")
private Course COURSE;
}
测试类:三种解决方案详细见代码
package com.star.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import com.google.gson.Gson;
public class JSonTest {
public static void main(String[] args) {
Course course = new Course("ENGLISH");
Student student = new Student("zhangsan", 18, course);
// 方案一 :new PascalNameFilter() fastjson出现重复引用或者循环引用
// 参考https://blog.csdn.net/u012060033/article/details/85999897
String jsonStr1 = JSON.toJSonString(student,new PascalNameFilter());
System.out.println(jsonStr1);
// 方案二: Gson 转换 更推荐
Gson gson = new Gson();
String jsonStr2 = gson.toJson(student);
System.out.println(jsonStr2);
// 方案三: 使用@JSonField(name = "NAME")
String jsonStr3 = JSON.toJSonString(student);
System.out.println(jsonStr3);
}
}
调试结果
方案一 :new PascalNameFilter() fastjson出现重复引用或者循环引用
参考http:// https://blog.csdn.net/u012060033/article/details/85999897



