1.背景
1.1 一个实体类
public class User {
@JSONField(name = "ID")
private String id;
private String name;
private String age;
@JSONField(name = "LIKE_FOOD")
private String likeFood;
private Job job;
public User(String id, String name, String age, String likeFood, Job job) {
this.id = id;
this.name = name;
this.age = age;
this.likeFood = likeFood;
this.job = job;
}
@Override
public String toString(){
return JSONObject.toJSONString(this,true);
}
}
1.2 用JSON.toJSONString()获取的结果为空
public class JsonTest {
public static void main(String[] args) {
User user = new User("1", "yang", "18", "apple", new Job("bank", "18000"));
System.out.println(user.toString());
}
}
2.解决
- 检查导入包类型,不要混用 com.alibaba.fastjson和org.json等
- 检查对象是否有get方法
3.结果
给user类加上@Data注解后再运行
{
"ID":"1",
"LIKE_FOOD":"apple",
"age":"18",
"job":{
"jobName":"bank",
"salary":"18000"
},
"name":"yang"
}