json - Spring - 返回原始 JSON 而不进行双重序列化
问题描述
我知道还有其他类似的帖子,但我没有找到任何可以帮助我找到解决这个特殊案例的方法。
我正在尝试HashMap<String, Object>
从我的控制器返回一个。该Object
部分是一个 JSON 字符串,但它被双重序列化并且不作为原始 JSON 字符串返回,因此不会以额外的引号和转义字符结尾。
控制器功能:
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HashMap<String, Object> heartbeat(){
String streamInfo = service.getStreamInfo();
String streamCursorInfo = service.getStreamCursorInfo();
String topicInfo = service.getTopicInfo();
String greeting = "This is a sample app for using Spring Boot with MapR Streams.";
HashMap<String, Object> results = new HashMap();
results.put("greeting", greeting);
results.put("streamInfo", streamInfo);
results.put("streamCursorInfo", streamCursorInfo);
results.put("topicInfo", topicInfo);
return results;
}
服务功能:
private String performCURL(String[] command){
StringBuilder stringBuilder = new StringBuilder();
try{
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process p = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = reader.readLine()) != null){
stringBuilder.append(line);
}
}
catch(Exception e){
LOGGER.error(ExceptionUtils.getRootCauseMessage(e));
}
return stringBuilder.toString();
}
我运行的 cURL 命令已经返回一个原始 JSON 字符串。所以我只是试图将它添加到 HashMap 以在心跳响应中返回。
但每次我运行这个,我的输出看起来像:
{
"greeting": "This is a sample app for using Spring Boot with MapR Streams.",
"streamCursorInfo": "{\"timestamp\":1538676344564,\"timeofday\":\"2018-10-04 02:05:44.564 GMT-0400 PM\",\"status\":\"OK\",\"total\":1,\"data\":[{\"consumergroup\":\"MapRDBConsumerGroup\",\"topic\":\"weightTags\",\"partitionid\":\"0\",\"produceroffset\":\"44707\",\"committedoffset\":\"10001\",\"producertimestamp\":\"2018-10-03T05:57:27.128-0400 PM\",\"consumertimestamp\":\"2018-09-21T12:35:51.654-0400 PM\",\"consumerlagmillis\":\"1056095474\"}]}",
...
}
如果我只返回单个字符串,例如streamInfo
然后它工作正常并且不添加额外的引号和转义字符。
谁能解释我缺少什么或需要做些什么来防止这种双重序列化?
解决方案
与其返回 a HashMap
,不如创建一个像这样的对象:
public class HeartbeatResult {
private String greeting;
... //other fields here
@JsonRawValue
private String streamCursorInfo;
... //getters and setters here (or make the object immutable by having just a constructor and getters)
}
@JsonRawValue
杰克逊将按原样序列化字符串。有关更多信息,请参阅https://www.baeldung.com/jackson-annotations。
推荐阅读
- xcode - 如何更改故事板的 segue 类型
- react-native-android - react-native 0.59.9 或更低版本的新 react-native-app
- sharepoint - infopath 开发的表格无法发布到 sharepoint 2019
- php - PHP会话文件的文件扩展名是什么?
- python - Python中比较两个字典的方法
- java - 按序数选择枚举;爪哇
- pdf - 我正在使用 Datalogics APDFL SDK。如何只打印包含某个单词的pdf页面?
- java - 将参数传递给枚举抽象方法
- php - 需要有关 Mikrotik PHP API 的帮助
- java - 如何使用java在两个元音之间打印一个字母