I need to serialize Java Object
to JSON
.
But when I use writeValueAsString
method this method returns me empty JSON Object.
Here is my @RestController
:
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:
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 am I doing wrong? How can I fix this?
2
Answers
I think you have a mistake in this line:
Maybe it should be:
You are trying to convert the
ObjectMapper
to json.What you want:
However your code is doing basically what the
RestTemplate
already does, and thus can be greatly simplified by removing theObjectMapper
as you don’t need it.