在Java中,處理復雜數據結構的VO(Value Object)類可以通過以下幾種方式:
public class UserVO {
private String name;
private int age;
private AddressVO address;
private List<String> hobbies;
// getters and setters
}
public class AddressVO {
private String street;
private String city;
private String country;
// getters and setters
}
public class OrderVO {
private String orderId;
private List<OrderItemVO> orderItems;
// getters and setters
}
public class OrderItemVO {
private String productId;
private String productName;
private int quantity;
private double price;
// getters and setters
}
public class UserVO {
private String id;
private String name;
private List<String> roles;
private Map<String, String> attributes;
// getters and setters
}
例如,使用Jackson庫將Java對象序列化為JSON字符串:
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
UserVO user = new UserVO();
user.setName("John Doe");
user.setRoles(Arrays.asList("admin", "user"));
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(user);
System.out.println(jsonString);
}
}
總之,處理復雜數據結構的VO類需要根據實際需求和場景來選擇合適的方法。在設計VO類時,應確保類的屬性能夠準確地表示數據結構,并遵循面向對象的設計原則。