Java 无JSON方案的响应的放心JSON验证

Java 无JSON方案的响应的放心JSON验证,java,json,rest,rest-assured,Java,Json,Rest,Rest Assured,我想检查JSON响应是否正确,至少是有效的,并且无法找到正确的方法来使用REST Assured实现这一点 我在中读了很多关于matchesJsonSchemaInClasspath的文章,但我还不想写完整的JSON模式 get("/products"). then(). assertThat(). body(matchesJsonSchemaInClasspath("products-schema.json")); 如果不添加该检查,将通过任何格式不正确的JSON检查

我想检查JSON响应是否正确,至少是有效的,并且无法找到正确的方法来使用REST Assured实现这一点

我在中读了很多关于matchesJsonSchemaInClasspath的文章,但我还不想写完整的JSON模式

get("/products").
    then().
    assertThat().
    body(matchesJsonSchemaInClasspath("products-schema.json"));
如果不添加该检查,将通过任何格式不正确的JSON检查-因此即使JSON无效,我也可以检查字段值,或者,例如数组大小

import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.get;
import static org.hamcrest.core.Is.is;


public class RestEndpointTest{
    @Test
    public void basic_rest_check() {
        get("/my_endpoint").
            then().
            assertThat().
            body("size()", is(2)).
            statusCode(200);
    }
}
即使是响应,测试也通过了:

[{},{}]MALFORMED

现在,这是微不足道的,但我发现,只有在几天之后,我才提出我的问题。因此,解决方案是使用matchesJsonSchema代替matchesJsonSchemaInClasspath

说明:关于

最基本的模式是一个空白JSON对象,它约束 不允许、不允许、不描述任何内容:

{}

另外还有一个选项,可以使用该内容{}创建文件,并通过matchesJsonSchemaInClasspath加载它

import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.get;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchema;

public class RestEndpointTest{
    @Test
    public void basic_rest_check() {
        get("/my_endpoint").
            then().
            assertThat().
            body(matchesJsonSchema("{}")).
            statusCode(200);
    }
}