FastJson 对象转 JSON 重新定义属性名
在使用 FastJson 将对象转换成 JSON 时,可以通过在对象的属性上使用 @JSONField 注解来重新定义属性名。
首先,需要在类的属性上使用 @JSONField 注解,指定 name 属性来重新定义属性名。例如:
public class User {
@JSONField(name = 'username')
private String name;
@JSONField(name = 'userage')
private int age;
// getter and setter methods
}
然后,使用 FastJson 的 toJSONString 方法将对象转换成 JSON 字符串时,会使用重新定义的属性名。例如:
User user = new User();
user.setName('John');
user.setAge(25);
String json = JSON.toJSONString(user);
System.out.println(json);
输出结果为:
{"username":"John","userage":25}
通过使用 @JSONField 注解,可以灵活地重新定义属性名,以满足特定的需求。
原文地址: https://www.cveoy.top/t/topic/qkLZ 著作权归作者所有。请勿转载和采集!