我需要发送一个缩小的JSON到rest服务,这似乎没问题,但是,当我将JSON打印到文件中时,会出现几个“ /”斜杠,将字段和文件分开,因为我是这种类型的新手。实现我很困惑...
基本上,我将对象添加到列表中,最后,我将通用列表转换为Json,这是将List对象转换为JSON的方法。
public String convertListToJson(List obj) throws IOException {
String jsonInString = null;
ObjectMapper mapper = new ObjectMapper();
mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);
mapper.configure(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID, true);
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
JsonNode jsonNode = mapper.readValue(jsonInString, JsonNode.class);
String json = jsonNode.toString();
return json;
}
String payload = convertListToJson(object);
System.out.println(payload);
这是在控制台上打印的结果
[{"id":12,"nomePeriodo":"2012","inicio":"2012-01-01T02:00:00Z","fim":"2012-12-31T02:00:00Z"},{"id":13,"nomePeriodo":"2013","inicio":"2013-01-01T02:00:00Z","fim":"2013-12-31T02:00:00Z"},{"id":14,"nomePeriodo":"2014","inicio":"2014-01-01T02:00:00Z","fim":"2014-12-31T02:00:00Z"},{"id":15,"nomePeriodo":"2015","inicio":"2015-01-01T02:00:00Z","fim":"2015-12-31T02:00:00Z"},{"id":16,"nomePeriodo":"2016","inicio":"2016-01-01T02:00:00Z","fim":"2016-12-31T02:00:00Z"},{"id":17,"nomePeriodo":"2017","inicio":"2017-01-01T02:00:00Z","fim":"2017-12-31T02:00:00Z"},{"id":18,"nomePeriodo":"2018","inicio":"2018-01-01T02:00:00Z","fim":"2018-12-31T02:00:00Z"}]
这是我用于打印到文件的方法
printJson(payload);
private void printJson(String payload) {
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File("c:\\server\\JSON.json"), payload);
} catch (IOException e) {
e.printStackTrace();
}
}
当我打印到文件时,结果如下:
"[{\"id\":12,\"nomePeriodo\":\"2012\",\"inicio\":\"2012-01-01T02:00:00Z\",\"fim\":\"2012-12-31T02:00:00Z\"},{\"id\":13,\"nomePeriodo\":\"2013\",\"inicio\":\"2013-01-01T02:00:00Z\",\"fim\":\"2013-12-31T02:00:00Z\"},{\"id\":14,\"nomePeriodo\":\"2014\",\"inicio\":\"2014-01-01T02:00:00Z\",\"fim\":\"2014-12-31T02:00:00Z\"},{\"id\":15,\"nomePeriodo\":\"2015\",\"inicio\":\"2015-01-01T02:00:00Z\",\"fim\":\"2015-12-31T02:00:00Z\"},{\"id\":16,\"nomePeriodo\":\"2016\",\"inicio\":\"2016-01-01T02:00:00Z\",\"fim\":\"2016-12-31T02:00:00Z\"},{\"id\":17,\"nomePeriodo\":\"2017\",\"inicio\":\"2017-01-01T02:00:00Z\",\"fim\":\"2017-12-31T02:00:00Z\"},{\"id\":18,\"nomePeriodo\":\"2018\",\"inicio\":\"2018-01-01T02:00:00Z\",\"fim\":\"2018-12-31T02:00:00Z\"}]"
因此,您可以使用这些\分隔json中的项目... 我做错什么了吗? 如果可能的话,我想将其从存档中删除