SpringMVC中返回值处理

对于springMVC处理方法支持支持一系列的返回方式:

  1. ModelAndView
  2. Model
  3. ModelMap
  4. Map
  5. View
  6. String
  7. Void

具体可参考链接:

http://my.oschina.net/bosscheng/blog/126941

以上是SpringMvc原生支持的返回类型,如果返回Json,可以用Json String或者Map,

还可以返回类,操作步骤见下面介绍。

 

需要注意的是,SpringMvc与Jackson结合使用时,如果返回的是一个Object、或者返回的Map中是Object型的,就需要对Object中的成员变量加注解,否则会报错:org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation,500 code error。 

原因是 Jackson 默认情况下不知道怎么去序列化,方法有:

1.为成员变量增加getter、setter方法

2. 或者也可以给field加上 @JsonProperty 注解,(也可在getter上加)  , 还能用它指定序列化时的属性名

 

@JsonProperty可以标注在field或者getter上,

Defines name of the logical property, i.e. Json object field name to use for the property(i.e. @JsonProperty("GID") ): if empty String (which is the default), will use name of the field that is annotated.

 

代码示例:

class ItemContent {

private int gid;

private int sid;

private Date createTime;

private String gname;

private String name;

private String nologinUrl;

 

@JsonProperty

int getGid() {

return gid;

}

 

void setGid(int gid) {

this.gid = gid;

}

 

@JsonProperty

int getSid() {

return sid;

}

.............................

 

@RequestMapping(value = "/dissert/getServerList.do")

@ResponseBody

public Object getServerList(HttpServletRequest request) {

Map<String, Object> resultMap = new HashMap<String, Object>();

..................................

        List<ItemContent> tempList = new ArrayList<ItemContent>();

for (GameServer gameServer : listServers) {

           ......................

ItemContent item = new ItemContent();

item.setGid(gameServer.getGid());

item.setGname(gameServer.getGname());

item.setSid(gameServer.getSid());

item.setName(gameServer.getName());

item.setCreateTime(gameServer.getCreateTime());

 

}

tempList.add(item);

}

}

resultMap.put("open", tempList);

return resultMap;

}

 

关于Jackson介绍,可参考:

http://unmi.cc/jackson-java-object-json-string/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值