在 Angular 的服务中,使用 deleteNulls 函数将请求体中的 null 删除,以避免发送 null 值到后台。 示例代码:
export class ProductService {
constructor(private http: HttpClient) { }
deleteNulls(obj: any): any { for (let key in obj) { if (obj.hasOwnProperty(key)) { if (obj[key] === null || obj[key] === undefined) { delete obj[key]; } } } return obj; }
updateProduct(product: Product): Observable${apiUrl}/products/${product.id}
, this.deleteNulls(product));
}
}
在 Spring JPA 的控制器中,使用 @JsonInclude(Include.NON_NULL) 注解忽略 null 值,只将不为 null 的值序列化返回给前端。 示例代码:
@RestController @RequestMapping("/products") public class ProductController {
@Autowired private ProductService productService;
@GetMapping("/{id}") public Product getProduct(@PathVariable("id") Long id) { return productService.getProduct(id); }
@PutMapping("/{id}") @JsonInclude(Include.NON_NULL) public Product updateProduct(@PathVariable("id") Long id, @RequestBody Product product) { product.setId(id); return productService.saveProduct(product); } }