如何使用Rest Assured从REST响应(json或xml)中提取字段值?

时间:2019-04-13 15:50:45

标签: rest-assured

我想从字符串类型的REST响应(json或xml)中提取值。我尝试了以下代码:

final Response response = new ResponseBuilder().setContentType("application/json").setStatusCode(200).setBody("{\"message\":\"hello\"}").build();
Object object = response.path("message");
System.out.println(object);

但它却令人沮丧

Exception in thread "main" java.lang.NullPointerException: Cannot invoke method getObjectMapperConfig() on null object
    at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:35)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
    at io.restassured.internal.RestAssuredResponseOptionsGroovyImpl.jsonPath(RestAssuredResponseOptionsGroovyImpl.groovy:358)

根本原因是RestAssuredResponseOptionsGroovyImpl中的RestAssuredConfig对象为空

那么,既然我已经有了字符串响应,如何在没有get()或post()的情况下从原始字符串响应正确构造Response对象?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

RestAssuredResponseOptionsImpl response = new RestAssuredResponseImpl();
response.setConfig(RestAssuredConfig.config());
response.setRpr(new ResponseParserRegistrar());
response.setContentType("application/json");
response.setStatusCode(200);
response.setContent("{\"message\":\"hello\"}");
Object message = response.path("message");
System.out.println(message);