简体   繁体   English

jayway jsonpath使用的默认类型?

[英]default type used by jayway jsonpath?

when I have a value such as 当我有一个像这样的价值

x = 0.5771622052130299

and I want to do the following, using spring 3.2 Resutlmatcher : 我想使用spring 3.2 Resutlmatcher执行以下操作:

.andExpect(jsonPath("$.[1].myX").value(myPojo.getMyX()))

where myPojo.getMyX returns a double, the test fails as the json is converted to a BigDecimal, with the error messaeg 其中myPojo.getMyX返回一个double,测试失败,因为json转换为BigDecimal,错误是messaeg

java.lang.AssertionError: 
For JSON path $.[1].myX type of value expected:
<class java.lang.Double> but was:<class java.math.BigDecimal>

How can I avoid this ? 我怎么能避免这个?

Use Hamcrest to create a custom matcher which casts to BigDecimal. 使用Hamcrest创建一个自定义匹配器,转换为BigDecimal。 Here is a tutorial: 这是一个教程:

Code from an unrelated question may also help. 来自不相关问题的代码也可能有所帮助。

References 参考

I had the same problem but I could not change the type Hamcrest was using for the JSON value (BigDecimal). 我有同样的问题,但我无法更改Hamcrest用于JSON值(BigDecimal)的类型。

Used this Workaround: 使用此解决方法:

public static final double DEFAULT_PRECISION = 0.000001;

public static Matcher<BigDecimal> closeTo(double value, double precision) {
    return BigDecimalCloseTo.closeTo(new BigDecimal(value), new BigDecimal(precision));
}

public static Matcher<BigDecimal> closeTo(double value) {
    return closeTo(value, DEFAULT_PRECISION);
}

... ...

.andExpect(jsonPath("$.values.temperature").value(closeTo(-13.26517)));

I had the same problem with different values where some were parsed as BigDecimal and some as double . 我对不同的值有同样的问题,其中一些被解析为BigDecimal ,一些被解析为double

So I choose not to use jsonPath, instead I convert the response to the actual object using MappingJackson2HttpMessageConverter : 所以我选择不使用jsonPath,而不是我转换为使用的实际对象的响应MappingJackson2HttpMessageConverter

public class ControllerTest {

    @Autowired
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;

    @SuppressWarnings("unchecked")
    protected <T> T toObject(MockHttpServletResponse response, Class<T> clazz) throws IOException{
        MockClientHttpResponse inputMessage = new MockClientHttpResponse(response.getContentAsByteArray(), 
                HttpStatus.valueOf(response.getStatus()));
        return (T) mappingJackson2HttpMessageConverter.read(clazz, inputMessage);
    }

    @Test
    public test(){
        MvcResult result = mockMvc.perform(get("/rest/url")...)
            .andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JSON_UTF8))
            .andReturn();

        MyPojoClass pojo = toObject(result.getResponse(), MyPojoClass.class);
        assertArrayEquals(new double[]{0.1, 0.2, 0.3}, pojo.getDoubleArray());
    }

}

因为它期待一个大十进制......你可以将双精度转换为大十进制

.andExpect(jsonPath("$.[1].myX", is(new BigDecimal(myPojo.getMyX()))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM