/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.view; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.AbstractView; import net.sf.json.JSON; import net.sf.json.JSONSerializer; import net.sf.json.JsonConfig; /** * A View that renders its model as a JSON object. * * @author Andres Almiray * @author Domenico Testa */ public class JsonView extends AbstractView { /** Default content type. Overridable as bean property. */ private static final String DEFAULT_JSON_CONTENT_TYPE = "application/json"; /** JSON rendering configuration profile */ private JsonConfig config; public JsonView() { super(); setContentType(DEFAULT_JSON_CONTENT_TYPE); } /** * Returns the JsonConfig instance for this serializer * * @return JsoConfig bean */ public JsonConfig getConfig() { return this.config; } public void setConfig(JsonConfig config) { this.config = config; } /** * Returns wether the JSONSerializer will ignore or not its internal * property exclusions. * * @deprecated */ public boolean isIgnoreDefaultExcludes() { return getConfig().isIgnoreDefaultExcludes(); } /** * Sets the group of properties to be excluded. * * @deprecated */ public void setExcludedProperties(String[] excludedProperties) { getConfig().setExcludes(excludedProperties); } /** * Sets wether the JSONSerializer will ignore or not its internal property * exclusions. * * @deprecated */ public void setIgnoreDefaultExcludes(boolean ignoreDefaultExcludes) { getConfig().setIgnoreDefaultExcludes(ignoreDefaultExcludes); } /** * Creates a JSON [JSONObject,JSONArray,JSONNUll] from the model values. */ protected JSON createJSON(Map model, HttpServletRequest request, HttpServletResponse response) { return defaultCreateJSON(model); } /** * Creates a JSON [JSONObject,JSONArray,JSONNUll] from the model values. */ protected final JSON defaultCreateJSON(Map model) { return JSONSerializer.toJSON(model, getConfig()); } /** * Returns the group of properties to be excluded. * * @deprecated */ protected String[] getExcludedProperties() { return getConfig().getExcludes(); } protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(getContentType()); JSON json = createJSON(model, request, response); json.write(response.getWriter()); } }