6

想在 Json 请求中传单个原始值,应该怎么做?

 3 years ago
source link: https://www.v2ex.com/t/798414
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Java

想在 Json 请求中传单个原始值,应该怎么做?

  dcsuibian · 2 天前 · 1193 次点击

据我所知,一个合法的 JSON 对象不仅可以是对象或数组,一些原始值也是可以的,比如字符串"foo"、数字3、布尔值true也应该都是合法的 JSON 值。

但是今天遇到了一个问题,我想设计一个接口来修改用户的头像。(头像 avatar 在数据库里也就是一个字符串)

想设计得尽量 RESTful 一点,用了 PUT 方法,请求路径大概是这样:

/api/users/{用户的 id}/avatar

虽然只是一个字符串,但想和其它接口一样都接收 JSON,返回 JSON 。所以不希望用text/plain而是一样采用application/json的 MIME 类型。我想,既然一个字符串也是合法的 JSON,那应该也没问题,因此就在 axios 的 data 里传了一个字符串:

image-20210827203655179

但是发现它给我自己转换掉了,而且不是JSON.stringify那种转换。

我本以为请求体里会是"a single string",但结果居然是a single string

image-20210827203932188

这根本就不是合法的 JSON 啊。

虽然再包一层也能解决,但很不舒服。

后来查了一下,似乎是 JSON 的定义出了问题:

image-20210827205946716

于是我就想问下,大佬们有遇到过这个问题吗?怎么优雅地解决这个问题呢?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK