标签: jsonpath

用jsonpath计算成员?

是否可以使用JsonPath计算成员数?

使用spring mvc test我正在测试一个生成的控制器

{"foo": "oof", "bar": "rab"}
Run Code Online (Sandbox Code Playgroud)

standaloneSetup(new FooController(fooService)).build()
            .perform(get("/something").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(jsonPath("$.foo").value("oof"))
            .andExpect(jsonPath("$.bar").value("rab"));
Run Code Online (Sandbox Code Playgroud)

我想确保生成的json中没有其他成员.希望通过使用jsonPath计算它们.可能吗?也欢迎替代解决方案.

java testing spring jsonpath spring-test-mvc

95
推荐指数
3
解决办法
6万
查看次数

如何测试JSON路径是否不包含特定元素,或者如果元素存在则为null?

我一直在为一个简单的spring Web应用程序编写一些简单的单元测试例程.当我在资源的getter方法上添加@JsonIgnore注释时,生成的json对象不包含相应的json元素.因此,当我的单元测试例程尝试测试它是否为null(这是我的情况的预期行为,我不希望密码在json对象中可用)时,测试例程会遇到异常:

java.lang.AssertionError:JSON路径没有值:$ .password,exception:路径没有结果:$ ['password']

这是我编写的单元测试方法,用is(nullValue())方法测试'password'字段:

@Test
public void getUserThatExists() throws Exception {
    User user = new User();
    user.setId(1L);
    user.setUsername("zobayer");
    user.setPassword("123456");

    when(userService.getUserById(1L)).thenReturn(user);

    mockMvc.perform(get("/users/1"))
            .andExpect(jsonPath("$.username", is(user.getUsername())))
            .andExpect(jsonPath("$.password", is(nullValue())))
            .andExpect(jsonPath("$.links[*].href", hasItem(endsWith("/users/1"))))
            .andExpect(status().isOk())
            .andDo(print());
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用jsonPath().exists()获得类似的异常,说明路径不存在.我正在分享更多的代码片段,以便整个情况变得更具可读性.

我正在测试的控制器方法看起来像这样:

@RequestMapping(value="/users/{userId}", method= RequestMethod.GET)
public ResponseEntity<UserResource> getUser(@PathVariable Long userId) {
    logger.info("Request arrived for getUser() with params {}", userId);
    User user = userService.getUserById(userId);
    if(user != null) {
        UserResource userResource = new UserResourceAsm().toResource(user);
        return new ResponseEntity<>(userResource, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用spring hateos资源汇编程序将实体转换为资源对象,这是我的资源类:

public class …
Run Code Online (Sandbox Code Playgroud)

java unit-testing spring-mvc jsonpath mockmvc

63
推荐指数
3
解决办法
5万
查看次数

如何在JSONPath中按字符串过滤?

我有来自Facebook API的JSON响应,如下所示:

{
  "data": [
     {
       "name": "Barack Obama", 
       "category": "Politician", 
       "id": "6815841748"
     }, 
     {
       "name": "Barack Obama's Dead Fly", 
       "category": "Public figure", 
       "id": "92943557739"
     }]
 }
Run Code Online (Sandbox Code Playgroud)

我想将JSONPath应用于它,只返回类别为"Politician"的结果.从我读过的内容看来,我需要这样做:

$.data[?(@.category=='Politician')]
Run Code Online (Sandbox Code Playgroud)

但根据我发现的测试工具,这不起作用.我发现了另一个问题,表明我应该使用"eq"而不是"==",但这也不起作用.我在这里弄错了什么?

json jsonpath

48
推荐指数
3
解决办法
9万
查看次数

SpringMVC/mockMVC/jsonpath比较字符串列表

我目前正在为Spring MVC项目编写一些单元测试.由于返回的媒体类型是JSON,我尝试使用jsonPath检查是否返回了正确的值.

我遇到的麻烦是验证字符串列表是否包含正确的(并且只有正确的)值.

我的计划是:

  1. 检查列表是否具有正确的长度
  2. 对于应该返回的每个元素,检查它是否在列表中

可悲的是,这些东西似乎都没有用.

这是我的代码的相关部分:

Collection<AuthorityRole> correctRoles = magicDataSource.getRoles();

ResultActions actions = this.mockMvc.perform(get("/accounts/current/roles").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()) // works
.andExpect(jsonPath("$.data.roles").isArray()) // works
.andExpect(jsonPath("$.data.roles.length").value(correctRoles.size())); // doesn't work

for (AuthorityRole role : correctRoles) // doesn't work
  actions.andExpect(jsonPath("$.data.roles[?(@=='%s')]", role.toString()).exists());
Run Code Online (Sandbox Code Playgroud)

只有前两个"期望"(isOk&isArray)才有效.其他的(长度和内容)我可以扭曲和转动但是我想要,他们没有给我任何有用的结果.

有什么建议?

java spring-mvc jsonpath

28
推荐指数
2
解决办法
4万
查看次数

如何将常量字符串与 jsonpath 连接

我有 AWS step machine,其中一个 step 用于使用 SNS 服务通知失败。我想从inputjson 中选择一些元数据到传出消息中。所以我试图将常量字符串与 jsonpath 连接起来,如下所示

"Notify Failure": {
      "Type": "Task",
      "Resource": "arn:aws:states:::sns:publish",
      "Parameters": {
        "Message.$": "A job submitted through Step Functions failed for document id $.document_id",
        "Subject":"Job failed",
        "TopicArn": "arn:aws:sns:us-west-2:xxxxxxx:xxxxxxxx"
      },
      "End": true
    }
Run Code Online (Sandbox Code Playgroud)

document_id输入 json 中的属性之一在哪里

但是,当我尝试保存状态机定义时,出现错误

您的 ASL 定义有问题,请检查并重试 'Message.$' 字段的值必须是有效的 JSONPath

jsonpath aws-step-functions

23
推荐指数
2
解决办法
6656
查看次数

无法编写jsonpath查询以返回已过滤数组的第一个对象

使用ashphy json路径评估器和以下JSON:

{ "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想写一个过滤类别的查询,例如"小说",然后只返回第一个元素.我似乎无法弄明白. …

jsonpath

21
推荐指数
1
解决办法
4676
查看次数

使用JSONPath从JSON对象获取单个值

我有以下JSON,我需要name使用JSONPath获取普通值:

{
  "single" : {
    "id" : 1, 
    "name" : "Item name"
  }
}
Run Code Online (Sandbox Code Playgroud)

我使用的表达式是$.single.name但我总是得到一个数组:

[ "Item name" ]
Run Code Online (Sandbox Code Playgroud)

而不是字符串值("Item name").

json jsonpath

19
推荐指数
2
解决办法
4万
查看次数

使用JSONPATH解析JSON数组文件

我想用JSONPath解析这个:

[
  [50.4154134372953,-1.28486558931069,"CLASS B",9,205,0,"UK",431500382,3,4],
  [50.3058858494047,-0.976070494820637,"CLASS B",9,239,0,"UK",2750350,21,2]
]
Run Code Online (Sandbox Code Playgroud)

你可以帮忙吗?

arrays json jsonpath

18
推荐指数
1
解决办法
5万
查看次数

JSONPath在Java中的基本用法

我将JSON作为字符串,将JSONPath作为字符串.我想用JSON路径查询JSON,将生成的JSON作为字符串.

我认为Jayway的json路径 是标准.在网上API,但是,并没有什么太大关系到你的Maven得到实际库.GrepCode的版本大致匹配.

看起来我应该能做到:

String originalJson; //these are initialized to actual data
String jsonPath;
String queriedJson = JsonPath.<String>read(originalJson, jsonPath);
Run Code Online (Sandbox Code Playgroud)

问题是,read基于什么JSONPath真正发现任何感觉最合适的回报(如List<Object>,String,double,等),因此我的代码会因某些查询的除外.假设有一些方法可以查询JSON并获取JSON,这似乎是合理的.有什么建议?

java json jsonpath

18
推荐指数
3
解决办法
7万
查看次数

使用jsonpath表达式的数组大小 - Stefan Goessner JsonPath

我使用Stefan Goessner的JsonPath找到数组或列表大小时遇到​​问题.我使用的是json-path-2.0.0版本.

我的jsonpath表达式是$.orders.length和JSON看起来像这样:

它失败了以下错误:

com.jayway.jsonpath.PathNotFoundException: Property ['length'] not found in path $['orders']
Run Code Online (Sandbox Code Playgroud)

而且我也尝试$.orders.length()了以下错误再次失败:

com.jayway.jsonpath.PathNotFoundException: Property ['length()'] not found in path $['orders']

请建议我如何使用Goessner的JsonPath表达式获取数组的长度.

[编辑]以下是我如何获得配置:

    com.jayway.jsonpath.Configuration conf = com.jayway.jsonpath.Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
    DocumentContext documentContext = JsonPath.using(conf).parse(orderJson);
    Object val = documentContext.read(jsonPathExpression);
Run Code Online (Sandbox Code Playgroud)

java arrays size json jsonpath

18
推荐指数
1
解决办法
3万
查看次数