如何使用 Java 中的 flexjson 通过 @JSON 注释控制序列化?\
javajsonobject oriented programmingprogramming更新于 2025/7/26 3:56:17
@JSON 注释 由 JSONSerializer 类使用,在序列化过程中排除或包含某个字段。我们可以使用 JSONSerializer 类的 serialize() 方法对目标实例进行浅层序列化。
语法
@Retention(value=RUNTIME)
@Target(value={FIELD,TYPE,METHOD})
public @interface JSON
示例
import flexjson.JSONSerializer;
import flexjson.JSON;
public class JSONAnnotationTest {
public static void main(String[] args) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
Employee emp = new Employee("Raja", "Ramesh", 30, "Hyderabad");
String jsonStr = serializer.serialize(emp);
System.out.println(jsonStr);
}
}
// Employee class
class Employee {
private String firstName, lastName, address;
private int age;
public Employee(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
@JSON(include=false)
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
@JSON(include=false) public String getAddress() {
return address;
}
}
输出
{
"age": 30,
"class": "Employee",
"firstName": "Raja"
}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

