java的bean对象里面有一个其他对象,通过自定义注解序列化,请给出java代码
时间: 2024-02-01 22:14:27 浏览: 88
下面是一个示例代码:
```java
public class Person {
private String name;
private int age;
@SerializeAnnotation
private Address address;
// 构造函数、getter和setter方法省略
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
public class Address {
private String city;
private String street;
// 构造函数、getter和setter方法省略
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SerializeAnnotation {
}
public class Serializer {
public String serialize(Object object) throws IllegalAccessException {
Class<?> clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
StringBuilder sb = new StringBuilder();
sb.append("{");
for (Field field : fields) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
if (field.isAnnotationPresent(SerializeAnnotation.class)) {
Object fieldValue = field.get(object);
sb.append("\"");
sb.append(field.getName());
sb.append("\":");
sb.append(serialize(fieldValue));
sb.append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
}
sb.append("}");
return sb.toString();
}
private String serialize(Object object) {
if (object instanceof String) {
return "\"" + object.toString() + "\"";
} else if (object instanceof Integer) {
return object.toString();
} else {
try {
return serialize(object);
} catch (IllegalAccessException e) {
e.printStackTrace();
return "";
}
}
}
}
```
在上面的示例代码中,`Person`类有一个`Address`对象,并且在`address`字段上使用了`SerializeAnnotation`注解。`Serializer`类是一个序列化工具类,它可以将标记了`SerializeAnnotation`注解的字段序列化为JSON字符串。在`serialize`方法中,如果需要序列化的对象是一个JavaBean,那么会递归调用`serialize`方法来进行序列化。注意,在`Address`类中并没有使用`SerializeAnnotation`注解,因此`Serializer`类不会将`Address`对象序列化为JSON字符串。
阅读全文