一、导包
链接:https://pan.baidu.com/s/1IKhGAnLO5PIcbOKKqMVKtA
提取码:lclc
二、测试
1、USer
package com.java.demo1.domain;
import java.util.Date;
public class User {
private String username;
private String password;
private String hobby;
private Date birthday;//支持这样的格式:1988/09/09;一般可以采用String来进行接收
private double score;//基础数据类型可以自动转换
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
2、Servlet
ckage com.java.demo1.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.java.demo1.domain.User;
@Controller //普通类被用Controller注释就变成了servlet
@Scope("prototype") //控制器一般都要使用多例,单例会影响效率
public class ControllerDemo2 {
//对象转成json格式
@RequestMapping(value = "/beanToJson.action") //为当前方法配置一个对外访问的虚拟路径
@ResponseBody //使用此注解可以将实体类、map、list变成Json
public User beanToJson() {
User user = new User();
user.setUsername("haoren");
user.setPassword("123");
user.setHobby("老大");
user.setScore(12.3);
return user;
}
//map转成json格式
@RequestMapping(value = "/mapToJson.action") //为当前方法配置一个对外访问的虚拟路径
@ResponseBody //使用此注解可以将实体类、map、list变成Json
public Map<String, String> mapToJson() {
Map<String, String> map = new HashMap<String, String>();
map.put("os", "windows");
map.put("version", "10");
return map;
}
//list转成json格式
@RequestMapping(value = "/listToJson.action") //为当前方法配置一个对外访问的虚拟路径
@ResponseBody //使用此注解可以将实体类、map、list变成Json
public List listToJson() {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("os", "windows");
map1.put("version", "10");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("os", "linux");
map2.put("version", "cent-os6.7");
List<Map<String, String>> list = new ArrayList<Map<String,String>>();
list.add(map1);
list.add(map2);
return list;
}
}
其它类型转