【问题标题】:Passing JSON String as value to a Spring data REST endpoint将 JSON 字符串作为值传递给 Spring 数据 REST 端点
【发布时间】:2019-07-09 08:38:14
【问题描述】:

我想在数据库列中存储一个包含有效 JSON 的字符串。 访问是通过@RepositoryRestResource 完成的。因此,如果我想更改列的值,请求将采用 JSON 格式,包括列名和新值。我想使用 MockMvc 为这个场景编写一个测试用例,向端点发送 PATCH 请求并等待响应。

我试图用引号转义值部分

一开始我有一个方法,它构建 JSON 请求体:

private String tableConfig() {
    return "{\n" +
        "\"tableConfig\" : " + "\"[\n"
        + "\"listOfProperties\" : [\n"
        + "\"aBooleanProperty\" : true,\n"
        + "\"anIntProperty\" : 5,\n"
        + "\"aStringProperty\" : \"stringValue\""
        + "]"
        + "]\"" +
        "}";
  }

接下来是测试用例:

@Test
  public void testUpdateTableConfig() throws Exception {
    mockMvc.perform(
        patch("http://localhost/api/usersettings/" + myEntity.getId())
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .characterEncoding("UTF-8")
            .content(tableConfig())
    )
        .andExpect(status().isNoContent())
        .andReturn();
  }

我预计不会收到任何内容响应。相反,我收到一个 400 Bad 请求,所以我假设 Spring 尝试将字符串中的 JSON 值映射到对象树或类似的东西。 有没有办法传递一个包含 JSON 作为值的 JSON 请求,并通过 Spring Data Rest 将原始 JSON 数据转换为字符串?

编辑:按要求添加网址

【问题讨论】:

  • 你能添加你的 端点实现吗?

标签: json spring spring-data-rest


【解决方案1】:

Json 无效。 实际表配置值为

{
"tableConfig" : "[
"listOfProperties" : [
"aBooleanProperty" : true,
"anIntProperty" : 5,
"aStringProperty" : "stringValue"]]"}

我觉得应该像下面这样

{
   "tableConfig":[
      {
         "listOfProperties":{
            "aBooleanProperty":true,
            "anIntProperty":5,
            "aStringProperty":"stringValue"
         }
      }
   ]
}

{
   "tableConfig":{
      "listOfProperties":{
         "aBooleanProperty":true,
         "anIntProperty":5,
         "aStringProperty":"stringValue"
      }
   }
}

您可以在在线 json 验证器上对其进行验证。

我建议使用 Json 库 Gson 或 Jackson。

【讨论】:

  • 好的,我可以尝试重新处理转义,但请注意,我想要的是:“tableConfig”的值应该是包含 JSON 的字符串,并且应该按原样存储在列中。使用您的解决方案,我可能会从 Spring 触发 JacksonMapper,将此 JSON 映射到其他内容。我希望将原始 JSON 存储在数据库中。
  • 是的,我明白了。您需要先检查“转义。由于 ListOfProperties 具有键值对,它应该是 [] 或对象列表 [ { key-value pairs} ]。您的请求标头包含“Content-Type:application/json”,Spring 尝试检查 Json 的验证并返回 400 错误(错误请求)。您还需要检查控制器部分。
  • 谢谢。转义是错误的,我也不得不转义\。
猜你喜欢
  • 2018-11-06
  • 1970-01-01
  • 2020-11-26
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
相关资源
最近更新 更多