SpringMVC返回JSON内容问题

郏高阳 发布于 2013/12/13 11:50
阅读 14K+
收藏 0

Controller如下:

请求正常:结果也拿到了,但是不是我想要的格式:

网上有所继承MappingJacksonJsonView修改filterModel方法,但是修改后结果就成了:

我想要的应该是model中的内容,{……}为什么会有那么多?谁知道该如何修改?

加载中
0
excepiton
excepiton

干嘛不用@ResponseBody

然后直接return user呢?

郏高阳
郏高阳
我是被逼的……
咯咯鸡
咯咯鸡
回复 @郏高阳 : 多此一举啊
郏高阳
郏高阳
我不想用这样的方式
0
大喵哥
大喵哥

引用来自“throwable”的答案

干嘛不用@ResponseBody

然后直接return user呢?

+1
0
SilenceSu
SilenceSu
@RequestMapping("yourFun")
      @ResponseBody
      public String yourFun() {
          return "{'a':1}";
       }



s
sune
这种方法不行 中文会乱码
0
bigtiger02
bigtiger02

最简单的直接用 @ResponseBody返回。
其二我经常使用的多视图,代码如下:
JsonView.java

package com.szfore.springmvc;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.AbstractView;

import com.google.gson.Gson;
/**
 * <b>function:</b>扩展AbstractView 实现JSON-lib视图
 * @author hoojo
 * @createDate 2011-4-28 下午05:26:43
 * @file MappingJsonlibVeiw.java
 * @package com.hoo.veiw.xml
 * @project SpringMVC4View
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class JsonView extends AbstractView {
    public static final String DEFAULT_CONTENT_TYPE = "application/json";
    public static final String HTML_CONTENT_TYPE = "text/html";
    public static final String DEFAULT_CHAR_ENCODING = "UTF-8";
    private String encodeing = DEFAULT_CHAR_ENCODING;
    
    private Object jsonData = null;
    private Map<String, Object> _jsonDataMap = new HashMap<String, Object>();
    
    public void setEncodeing(String encodeing) {
        this.encodeing = encodeing;
    }
    private Set<String> renderedAttributes;
    public JsonView() {
        setContentType(DEFAULT_CONTENT_TYPE);
    }
    public JsonView(Object data) {
    	setContentType(DEFAULT_CONTENT_TYPE);
    	this.jsonData  =data;
    }
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	response.setCharacterEncoding(encodeing);
    	response.setContentType(getContentType());
    	
    	PrintWriter out = response.getWriter();
    	if(jsonData != null){
    		out.print(new Gson().toJson(jsonData));
    	}else if(!_jsonDataMap.isEmpty()){
    		out.print(new Gson().toJson(_jsonDataMap));
    	}else {
    		model = filterModel(model);
            out.print(new Gson().toJson(model));
    	}
    }
    
    /**
     * Filters out undesired attributes from the given model.
     * <p>Default implementation removes {@link BindingResult} instances and entries not included in the {@link
     * #setRenderedAttributes(Set) renderedAttributes} property.
     */
    protected Map<String, Object> filterModel(Map<String, Object> model) {
        Map<String, Object> result = new HashMap<String, Object>(model.size());
        Set<String> renderedAttributes =
                !CollectionUtils.isEmpty(this.renderedAttributes) ? this.renderedAttributes : model.keySet();
        for (Map.Entry<String, Object> entry : model.entrySet()) {
            if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) {
                result.put(entry.getKey(), entry.getValue());
            }
        }

        return result;

    }
    
    public void setJsonData(Object jsonData){
    	this.jsonData = jsonData;
    }
    
    public static JsonView returnJson(Object jsonData){
    	JsonView jsonView = new JsonView();
    	jsonView.setJsonData(jsonData);
    	return jsonView;
    }
    
    public JsonView put(String key, Object value)
    {
    	_jsonDataMap.put(key, value);
    	return this;
    }
}
MultiViewResover.java
package com.szfore.springmvc;

import java.util.Locale;
import java.util.Map;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

/**
 * @author Jeson
 * @blog:http://www.gbsou.com
 * @date:Oct 20, 2009 8:39:27 AM
 * @version :1.0
 * 
 */
public class MultiViewResover implements ViewResolver {

	private Map<String, ViewResolver> resolvers;
	
	private final static String DEFAULT_RESOLVER = "jsp";
	private final static String JSON_RESOLVER = "json";
	private final static String JSON_VIEW_NAME = "jsonView";
	
	/*
	 * 自定义resolve类默认为jsp视图,其余视图用下划线分隔
	 */
	@Override
	public View resolveViewName(String viewName, Locale locale) throws Exception {
		//判断是否为json
		String tmpViewName = viewName.trim().toLowerCase();
		if(JSON_RESOLVER.equals(tmpViewName)){
			ViewResolver resolver = resolvers.get(JSON_RESOLVER);
			return resolver.resolveViewName(JSON_VIEW_NAME, locale);
		}
		//若无下划线,默认转向jsp视图
		int n = viewName.lastIndexOf("_"); 
		if (n == (-1)){
			ViewResolver resolver = resolvers.get(DEFAULT_RESOLVER);
			return resolver.resolveViewName(viewName, locale);
		}
		//有的话截取下划线后面的字符串 这里一般是jsp,ftl,vm与配置文件中的<entry key="ftl">的key匹配
		String suffix = viewName.substring(n + 1);
		// 根据下划线后面的字符串去获取托管的视图解析类对象
		ViewResolver resolver = resolvers.get(suffix);
		// 取下划线前面的部分 那时真正的资源名.比如我们要使用hello.jsp 那viewName就应该是hello_jsp
		viewName = viewName.substring(0, n);
		if (resolver != null){
			return resolver.resolveViewName(viewName, locale);
		}
		return null;
	}

	public Map<String, ViewResolver> getResolvers() {
		return resolvers;
	}

	public void setResolvers(Map<String, ViewResolver> resolvers) {
		this.resolvers = resolvers;
	}
}
xml配置
<!-- 多视图 -->
	<bean name="jsonView" class="com.szfore.springmvc.JsonView">
	</bean>
	<bean id="viewResolver" class="com.szfore.springmvc.MultiViewResover">
		<property name="resolvers">
			<map>
				<entry key="jsp">
					<bean
						class="org.springframework.web.servlet.view.InternalResourceViewResolver">
						<property name="prefix" value="/" />
						<property name="suffix" value=".jsp" />
					</bean>
				</entry>
				<entry key="json">
					<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
					</bean>
				</entry>
			</map>
		</property>
	</bean>
使用方法:
@RequestMapping("/test")
public JsonView test(){
  return new JsonView(new User());
}



0
小小志
小小志
支持一楼
0
开源中国时时彩理财师
开源中国时时彩理财师
是不是想这样用?找我呗
@RequestMapping(value="/user", method=RequestMethod.GET)
public String getUser()
{
	User user = new User();
		
	user.setUserName("userName");
	user.setPassword("password");
	user.setAge(22);
	user.setSex("男");
	user.setBirthday("2013-11-11");
		
	return "json:" + JSONUtils.jsonSucess(user);
}



开源中国时时彩理财师
开源中国时时彩理财师
@郏高阳 这样用的目的就是返回JSONObject
郏高阳
郏高阳
我还是返回JSONObject
返回顶部
顶部