如何转换包含对象列表的POJO

时间:2013-07-29 10:34:41

标签: java json extjs jackson pojo

public class CustomerAddress {
    private Customer customer;
    //I think the problem is in hear becouse jackson does not know how to serialize this object list
    private List<Address> address;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public List<Address> getAddress() {
        return address;
    }

    public void setAddress(List<Address> address) {
        this.address = address;
    }    
}

public class Address{

    private Integer id;    
    private Customer customer;
    private AddressType addressType;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }       
    public Customer getCustomer() {
        return customer;
    }
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public AddressType getAddressType() {
        return addressType;
    }
    public void setAddressType(AddressType addressType) {
        this.addressType = addressType;
    }
}

public class Customer {

    private Integer id;
    private String firstName;
    private String middleName;   
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getMiddleName() {
        return middleName;
    }
    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }
}

我从数据库表单中获取数据,然后将其发送回页面

CustomerAddress customerAddress = customerAddressService.getCustomerAddress(22);
Map<String, Object> map = getMapCustomerAddress(customerAddress);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
return mapper.writeValueAsString(map);

这是我返回地图的方法

private Map<String, Object> getMapCustomerAddress(CustomerAddress customerAddress) throws IOException {

    Map<String, Object> modelMap = new HashMap<String, Object>(3);
    modelMap.put("total", 1);
    modelMap.put("data", customerAddress);
    modelMap.put("success", true);

    return modelMap;
}

我遇到错误

java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/JsonMappingException$Reference
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:613)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:142)

任何机构都可以告诉我如何转换这个&#34; CustomerAddress&#34;使用杰克逊进入json课程

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,它与循环引用有关。我怀疑你的问题与循环引用有关:

public class Address {

private Integer id;    
private Customer customer;

Address返回到Customer有一个循环引用,我假设它与Customer处的CustomerAddress引用相同:

public class CustomerAddress {
private Customer customer;

以某种方式打破循环引用,它应该有效。