如何在RestController中映射嵌套的JSON?

时间:2017-05-19 22:47:21

标签: json spring spring-boot http-post spring-restcontroller

我正在尝试使用Spring Boot和RestController将嵌套的JSON保存在数据库中。那些JSON看起来像这样:

{ 
 "name": "Car 1", 
 "plate_number": "PLATE NUMBER",
 "owner": { 
            "first_name": "First name",
            "last_name": "Last name"
          }
}

使用RestController中spring提供的自动映射很容易映射正常字段(名称和板号):

public Car createProduct(Car car) {

}

但是现在,我怎样才能将对象所有者映射到它自己的类CarOwner?(我需要提一下,我有多个使用这种方法的类,所以通用的方法非常有用)

修改

我的实体看起来像这样:

@Entity
@Table(name = "cars")
public class Car extends BaseEntityWithName {

    private String name;

    private String plateNumber;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "owner_id")
    private Owner owner;

}

@Entity
@Table(name = "car_owners")
public class CarOwner extends BaseEntityWithName {

    private String firstName;
    private String lastName;

    // Constructor, setters, getters
}

我正试图在控制器中做这样的事情:

@RestController
@RequestMapping("/cars")
public class CarController {

    @Autowired
    private CarService carService;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public ProductModel createItem(Car car) {
        // How do I create the owner using the JSON parameters 
        // provided in the nested JSON?

        car.setOwner(owner); // Owner created above
        return carService.save(car);
    }

}

编辑2 我的两个服务看起来像这样。两者的结构相同。

@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private ProductManufacturerRepository productManufacturerRepository;

    @Autowired
    private CarRepository carRepository;

    @Override
    public List<Car> findAll() {
        return carRepository.findAll();
    }

    @Override
    public Car findOne(Long id) {
        return carRepository.findOne(id);
    }

    @Override
    @Transactional
    public Car save(Car car) {
        return carRepository.save(car);
    }

    @Override
    public void removeOne(Long id) {
        carRepository.delete(id);
    }
}

2 个答案:

答案 0 :(得分:0)

从您的服务层我可以看到您只需要保存所有者类。优选地,这将是一个单独的所有者服务,但这足以开始。

@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private ProductManufacturerRepository productManufacturerRepository;

    @Autowired
    private CarRepository carRepository;

    @Override
    public List<Car> findAll() {
        return carRepository.findAll();
    }

    @Override
    public Car findOne(Long id) {
        return carRepository.findOne(id);
    }

    @Override
    @Transactional
    public Car save(Car car) {
        Owner person = car.getOwner();
        ownerRepository.save(person);
        return carRepository.save(car);
    }

    @Override
    public void removeOne(Long id) {
        carRepository.delete(id);
    }
}

答案 1 :(得分:0)

解决了这个问题。我的课程配置不正确。