0

I have written a function to create the body for a POST request sent to a restful webservice as below. The function,refers an array [temp], sends it to a another function which removes null values and return a clean array [tempArray]. Then I create the request body depending on the number of parameters in temp array.

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
}

the sample request i make---------------------------------

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

The status returned is 400. But when I replace body(createBody()) with body({\"email\":\"test@test.com\"}") the request is a success. [When i pass the parameters as a string without passing the return string from the function]. Note that the two strings are identical.

Please help me find me a solution for this.

Thanks in advance..

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
user1510519
  • 15
  • 1
  • 5

1 Answers1

0

You should consider to use a dedicated tool to build your JSON content.

Jackson is a good match since it allows to generate JSON content from beans / POJOs. You can configure the convertion to exclude null values (see this link How to tell Jackson to ignore a field during serialization if its value is null?).

To use it, simple add the dependency in your Maven pom.xml file, see this link: https://github.com/FasterXML/jackson-docs/wiki/Using-Jackson2-with-Maven.

Here is a sample of use:

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();
}

The content of the bean:

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

    public String getEmail() {
        return email;
    }

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

With the following Maven dependency:

<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>

If you want to build a low level tool. You can leverage a JSON parser like this one: http://www.json.org/java/index.html.

To use it, simple add the dependency in your Maven pom.xml file, see this link: http://mvnrepository.com/artifact/org.json/json.

Here is a sample of use:

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);

With the following Maven dependency:

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

Hope it helps you, Thierry

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360