Home > Software design >  Java: Request body in XML or JSON without using String
Java: Request body in XML or JSON without using String

Time:11-03

I am developing an application using Spring Boot (with Java). This application has to call several external services and each of these services requires a complicated body (in json or xml) (this input can vary! The fields I pass to it are not required so sometimes I might even pass a subset of these fields). These are examples of inputs that services can receive:

{
  "field1": "string",
  "field2": "string",
  "field3": "string",
  "field4": 0,
}

<input>
    <input1>my_string</input1>
    <input2>my_string</input2>
</input>

I use RestTemplate to make HTTP calls. This is an example. I use a Java String to model the HTTP body (but it has the big defect that it is not editable but hard-coded!):

    String Jsonbody = "{\r\n"
              "  \"field1\": \"" myString1 "\"\r\n" 
              "  \"field2\": \"" myString2 "\"\r\n"
              "}";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<String>(Jsonbody, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<MyResponseClass> response = restTemplate.postForEntity(url, request, MyResponseClass.class);

It is very bad to have a body hard-coded like this in the JsonBody variable. What is the way to have an object in which I dynamically insert strings and which automatically creates a JSON object (which I can then convert to a string to put in the .postForEntity method)? The same issue for XML input types.

CodePudding user response:

There are multiple libraries as Gson or Jackson that actually allow you to work with JSON as they are Java Objects to finally serialize them as a body.

If you want to give it a try, you would just need to include Gson as dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Then you'd have to create a POJO for your POST body:

public class JsonBody {

  private List<String> fields = new LinkedList<>();

  void addField(String field) {
    fields.add(field);
  }

}

And feel free to add as many String as you want that it will be parsed afterwards.

JsonBody jsonBody = new JsonBody();
Gson gson = new Gson();

jsonBody.addField(myString1);
jsonBody.addField(myString2);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<String>(gson.toJson(jsonBody), headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<MyResponseClass> response = restTemplate.postForEntity(url, request, MyResponseClass.class);

This would set your JSON to:

{
  fields: [
    contentMyString1,
    contentMyString2
  ]
}

Taking the previous example into account, you can just modify and format your JSON as you want in the form of a POJO and use the Gson::toJson(String) function from Gson.

Of course if you just create a POJO as:

public class JsonBody {

  private String field1;
  private String field2;
  private String field3;
  private Integer field4;

}

Then the output would be the same one than you have in your initial example.

CodePudding user response:

Use the ObjectMapper class like this ...

ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);

The output will be

{"color":"yellow","type":"renault"}

Here's some more data on the topic https://www.baeldung.com/jackson-object-mapper-tutorial

Same approach is used for mapping objects into XML (https://www.baeldung.com/jackson-xml-serialization-and-deserialization)

  • Related