如何在作为 REST API 的响应返回时将一个对象写入另一个对象?

How to write an object into another while returning as a response of REST API?

我有两个 类 address & customertoString() 方法。客户和地址是一对一的映射。因此,每个客户都包含一个地址。让我们看看下面的...

I would like to have a http response as:-

{
    "id": customerId,
    "addressId": addressId,
    "firstName": "first_name",
    "lastName": "last_name",
    "address": {
         "id": addressId,
         "street": "street",
         "city": "city",
         "country": "country",
         "postalCode": "postal_code"
    } 
}

Address.java

package com.maxpro.models;

import javax.persistence.*;


@Entity
public class Address {

    private Long id;
    private String street;
    private String city;
    private String country;
    private String postalCode;

    // getters & setters

    @Override
    public String toString () {
        return String.format("address[id='%d', street='%s', city='%s', country='%s', postalCode='%s']",
                                      id, street, city, country, postalCode
        );
    }

}

Customer.java

package com.maxpro.models;

import javax.persistence.*;


@Entity
public class Customer {

    private Long id;
    private Long addressId;
    private String firstName;
    private String lastName;

    private Address address;

    // getters & setters
    @Override
    public String toString() {
        return String.format(
                "customer[id=%d, addressId=%d, firstName='%s', lastName='%s', address='%s']",
                             id, addressId, firstName, lastName, address
        );
    }

}

CustomerRestController.java

package com.maxpro.controllers.rest;

import com.maxpro.models.Address;
import com.maxpro.models.Customer;
import com.maxpro.repositories.AddressRepository;
import com.maxpro.repositories.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/api/customers")
public class CustomerRestController {

    // CustomerRepository extends CrudRepository<Customer, Long>
    @Autowired
    private CustomerRepository customerRepository;

    // AddressRepository extends CrudRepository<Address, Long>
    @Autowired
    private AddressRepository addressRepository;

    @RequestMapping("/customer-with-address/{customerId}")
    public Customer getCustomerWithAddress(@PathVariable("customerId") Long customerId) {
        return customerRepository.findOne(customerId);
    }

}

It shows:

Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.maxpro.models.Customer["address"]->com.maxpro.models.Address_$$_jvst556_1["handler"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.maxpro.models.Customer["address"]->com.maxpro.models.Address_$$_jvst556_1["handler"])

如何获得预期的结果?这意味着,如何将 address 对象放入 HTTP 响应中的 customer

您需要急切地获取子项,即客户的地址。由于您使用的是 JPA,因此这两个实体之间应该存在关系。它可以是一对多或一对一..

确定您要在两个实体之间维护的关系,只需指定获取类型。 例如:@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)