如何区分从 JSON 解析的有意为空值和不存在的字段?

huangapple 未分类评论57阅读模式
英文:

how to make distinction between an intentional null and a non present field parsed from json as null?

问题

我正在开发一个CRUD网络应用程序,它暴露一个REST端点,用于更新MongoDB集合中的现有文档。

前端发送的JSON对象仅包含需要更改的字段。

由于JSON解析器将初始化JSON对象中不存在的所有字段为null,我如何知道一个字段是否为null,因为用户希望删除该值,还是因为不需要更新它?

答案可能是无法知道,但我实际上想问的是:人们通常如何处理这种情况?

每次发送完整对象并在数据库中完全替换它对我来说不是一个选项,由于几个原因(良好实践、性能以及前端的工作方式)。

我想到了一个可能行得通但我不是很满意的解决方案:

  1. 为每个非必填字段添加一个额外的布尔标志(对于必填字段,我知道我不能删除该值)
  2. 在MessageBodyReader中拦截JSON并自行解析JSON
  3. 如果JSON中的字段为null,则将额外的标志设置为true,表示“要删除”

这是目前为止我能想到的“最清洁”的解决方案,但它需要很多额外的工作,我希望我能找到另一种方法。

提前感谢您的任何建议。

英文:

I'm developing a CRUD web application which exposes a REST endpoint to update an existing document in a MongoDB collection.

The json object sent by the frontend only contains the fields that have to change.

Since the json parser will initialize all fields that were non present in the json object to null, how can I know if a field is null because the user wanted to remove that value, or because it doesn't have to be updated ?

The answer is probably that there is no way to know, but then my question rather is: how do people usually handle that case ?

Sending the full object each time and replacing it entirely in the DB is not an option for me, for several reasons (good practices, performance and also the way the frontend works).

I thought of a solution that could work but I'm not really happy with it:

  1. add an extra boolean flag for each field that is not mandatory (for the mandatory ones, I know I can't delete the value)
  2. intercept the json in a MessageBodyReader and parse the json myself
  3. if a field is present with null in the json, set the extra flag to true to mark it as "to delete"

This is the "cleanest" solution I could think of so far, but it requires so much extra work that I hope I can find another way.

Thanks in advance for any advise.

huangapple
  • 本文由 发表于 2020年7月27日 18:19:33
  • 转载请务必保留本文链接:https://java.coder-hub.com/63113263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定