json - 将 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
解决方案
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。
推荐阅读
- reactjs - 如何在渲染内触发 Reactjs onClick 而不是返回?
- sql - 多对多关系表的约束——两个相关记录都需要引用相同的依赖记录?
- php - PhP 的邮件功能显示我的 CPanel 登录信息
- flutter - 如何增加 Flutter 中 ElasticOutCurve 的最高超调范围?
- matlab - MATLAB - 如何沿给定公式的表面切割网格?
- c# - IMongoCollection Substitute 上的模拟数据
- c# - 具有动态策略提供程序授权的 .NET Core 多重身份验证
- ruby-on-rails - Ruby:如何记录对象并将其重用于测试?
- angular - 使用实体适配器 ngrx 创建子减速器
- python-3.x - 在 psycopg2 中使用循环查询和数据元组的更新语句失败