我有一个项目,我正在使用Spring MVC+Jackson构建REST服务.假设我有以下java实体

public class MyEntity {
    private Integer id;
    private boolean aBoolean;
    private String aVeryBigString;
    //getter & setters
}

Sometimes, I just want to update the boolean value, and I don't think that sending the whole object with its big string is a good idea just to update a simple boolean. So, I have considered using the PATCH HTTP method to only send the fields that need to be updated. So, I declare the following method in my controller:

@RequestMapping(method = RequestMethod.PATCH)
public void patch(@RequestBody MyVariable myVariable) {
    //calling a service to update the entity
}

The problem is: how do I know which fields need to be updated? For instance, if the client just wants to update the boolean, I will get an object with an empty "aVeryBigString". How am I supposed to know that the user just wants to update the boolean, but does not want to empty the string?

I have "solved" the problem by building custom URLs. For instance, the following URL: POST /myentities/1/aboolean/true will be mapped to a method that allows to only update the boolean. The problem with this solution is that it is not REST compliant. I don't want to be 100% REST compliant, but I do not feel comfortable with providing a custom URL to update each field (especially given that it causes problems when I want to update several fields).

另一个解决方案是将"MyEntity"拆分为多个资源,只更新这些资源,但我觉得这没有意义:"MyEntity"is是一个普通的资源,而不是composed of个其他资源.

那么,有没有一种优雅的方法来解决这个问题呢?

推荐答案

您可以将布尔值更改为布尔值,并为所有不想更新的字段分配空值.唯一的一个非空值将定义您要更新哪个字段客户端.

Json相关问答推荐

如何获取brew list作为JSON输出

Jolt变换将字段移动到数组的每个元素中

使用快速json库编写json可以消除所有缩进

(已回答)JSON 读取函数返回未定义而不是预期值 - Typescript

如何使NiFi将数据库单列中的多个值转化为Solr索引中的数组?

匹配来自不同数组的值

使用 jq 工具将文本从 txt 文件转换为 json

数据清理设计不良的 JSON 数据 - 需要有关最佳策略的建议

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

添加到数组时出错:找不到Add的重载和参数计数:1

Flutter:在本地文件 json 中搜索特殊的阿拉伯字符

在循环中将变量添加到 bash 数组

如何使用 LINQ 在 C# 中重构对象?

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

在android中读取Json数组

Spring restTemplate 获取原始 json 字符串

如何从 JSON 响应中提取单个值?

JSON 格式的 Amazon S3 响应?

强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)

使用 JSON.NET 序列化/反序列化对象字典