Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why objectmapper writevalueasstring return empty string?

I need to serialize Java Object to JSON, but when i use writevalueasstring method this method returns me empty json object. Here is my rest controller

 public String getReportsFromReporter(@PathVariable(name = "from")String from, 
  @PathVariable(name = "to")String to) throws IOException {
    String url = "example.com";
    ObjectMapper objectMapper = new ObjectMapper();
    ObjectForRequestToReporter objectForRequestToReporter =
            new ObjectForRequestToReporter();
    objectForRequestToReporter.setToken(somedata);
    objectForRequestToReporter.setEmployee(somedata);
    objectForRequestToReporter.setFrom(from);
    objectForRequestToReporter.setTo(to);
    String jsonObject = objectMapper.writeValueAsString(objectMapper);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>(jsonObject, httpHeaders);
    String ans = restTemplate.postForObject(url , entity, String.class);
    String test = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectMapper);
    System.out.println(test);
    System.out.println(jsonObject);
    return ans;

System.out.println shows this

 { }
 {}

Gradle depedencies

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

implementation("com.fasterxml.jackson.core:jackson-annotations:2.14.2")
implementation("com.fasterxml.jackson.core:jackson-core:2.14.2")
implementation("com.fasterxml.jackson.core:jackson-databind:2.14.2")

Object class for serialize

 @Data
 public class ObjectForRequestToReporter {

private String token;
private String employee;
private String from;
private String to;
private final int work_after = 0;
}

What i`m doing wrong?How i can fix this?

>Solution :

I think you have a mistake in this line:

String jsonObject = objectMapper.writeValueAsString(objectMapper);

Maybe it should be:

String jsonObject = objectMapper.writeValueAsString(objectForRequestToReporter);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading