我需要将Java Object
序列化为JSON
。
但是当我使用writeValueAsString
方法时,这个方法返回空的JSON Object。
以下是我的@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
显示:
{ }
{}
年级依赖性:
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")
用于序列化的对象类:
@Data
public class ObjectForRequestToReporter {
private String token;
private String employee;
private String from;
private String to;
private final int work_after = 0;
}
我做错了什么?我该怎么解决这个问题?
2条答案
按热度按时间3htmauhk1#
我觉得你这一行有个错误:
也许应该是:
fcipmucu2#
您正在尝试将
ObjectMapper
转换为json。你想要的:
但是,您的代码基本上是在做
RestTemplate
已经做的事情,因此可以通过删除不需要的ObjectMapper
来大大简化。