无法将方法创建的字符串传递给休息请求

时间:2015-03-16 11:02:40

标签: java rest

我已经编写了一个函数来为发送到restful webservice的POST请求创建一个body,如下所示。该函数引用一个数组[temp],将其发送到另一个函数,该函数删除空值并返回一个干净的数组[tempArray]。然后我根据临时数组中的参数数量创建请求体。

public String createBody()
    throws FileNotFoundException {
    StringBuilder sb = new StringBuilder();
    // function to remove null values and clean array [this has no issues]
    tempArray = cleanArray(temp);
    //check parameter count is valid
    if (tempArray.length % 2 == 0) {
        for (int i = 0; i < tempArray.length; i++) {
            if (i == 0) {
                body = sb.append("{\\").append("\"").append(tempArray[i]).toString();
            }
            //{\"key1\":\"value1\",\"key2\":\"value2\"}"
            else if ((i != 0) && (i != (tempArray.length - 1))) {
                if (i % 2 != 0) {
                    body = sb.append("\\\":\\\"").append(tempArray[i]).toString();
                } else if (i % 2 == 0) {
                    body = sb.append("\\\",\\\"").append(tempArray[i]).toString();
                }
            } else if (i == (tempArray.length - 1)) {
                body = sb.append("\\\":\\\"").append(tempArray[i]).append("\\\"}").toString();
            }
        }
        return body;
    } else {
        return "Invalid";
    } //test this
}

我发出的样本请求---------------------------------

given().headers("Content-Type", "application/json", "Authorization", "------")
                    .body(createBody()).when().post(BaseUrl)
                    .then()
                            .assertThat().statusCode(200);

返回的状态是400。 但是当我用body(createBody())替换body({\"email\":\"test@test.com\"}")时,请求就会成功。 [当我将参数作为字符串传递而不从函数传递返回字符串时]。请注意,这两个字符串是相同的。

请帮我找到解决方案。

提前致谢..

1 个答案:

答案 0 :(得分:0)

您应该考虑使用专用工具来构建JSON内容。

Jackson是一个很好的匹配,因为它允许从beans / POJO生成JSON内容。您可以将convertion配置为排除空值(请参阅此链接How to tell Jackson to ignore a field during serialization if its value is null?)。

要使用它,只需在Maven pom.xml文件中添加依赖项,请参阅以下链接:https://github.com/FasterXML/jackson-docs/wiki/Using-Jackson2-with-Maven

以下是使用示例:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);

TestBean bean = new TestBean();
bean.setEmail("test@test.com");
bean.setOtherField(null);

try {
    String jsonContent = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean);
    System.out.println("jsonContent = " + jsonContent);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

bean的内容:

public class TestBean {
    private String email;
    private String otherField;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    (...)
}

具有以下Maven依赖关系:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.2.2</version>
</dependency>

如果您想构建一个低级别的工具。您可以利用像这样的JSON解析器:http://www.json.org/java/index.html

要使用它,只需在Maven pom.xml文件中添加依赖项,请参阅以下链接:http://mvnrepository.com/artifact/org.json/json

以下是使用示例:

JSONObject jsonObj = new JSONObject();

String[] tempArray = new String[] {
        "email", "test@test.com"
};
if (tempArray.length % 2 == 0) {
    int i = 0;
    while (i < tempArray.length) {
        String key = tempArray[i];
        String value = tempArray[i + 1];
        jsonObj.put(key, value);
        i += 2;
    }
}
String jsonContent = jsonObj.toString(4);
System.out.println("jsonContent = " + jsonContent);

具有以下Maven依赖关系:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

希望它可以帮到你, 亨利