Java tutorial
/* werecloud provides a simple API to the VMWare vCenter data. Copyright (C) 2015 NigelB This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package werecloud.api.view; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.springframework.web.servlet.View; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.util.Map; /** * <code>JSONView</code> * Date: 28/12/2014 * Time: 10:58 AM */ public class JSONView implements View { private boolean outputNulls = false; @Override public String getContentType() { return "application/json"; } @Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { ServletOutputStream out = response.getOutputStream(); if (model.containsKey("model")) { ObjectMapper mapper = new ObjectMapper(); //use ISO-8601 dates instead of timestamp mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, outputNulls); ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue(bos, model.get("model")); response.setContentLength(bos.size()); response.setContentType("application/json"); out.write(bos.toByteArray()); return; } throw new Exception("Could not find model."); } public boolean isOutputNulls() { return outputNulls; } public void setOutputNulls(boolean outputNulls) { this.outputNulls = outputNulls; } }