首页 > 解决方案 > 将 JSON 字符串作为值传递给 Spring 数据 REST 端点

问题描述

我想在数据库列中存储一个包含有效 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 数据转换为字符串?

编辑:按要求添加 URL

标签: jsonspringspring-data-rest

解决方案


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。


推荐阅读