第一步:下載並導入jackson-all-1.9.0.jar包, 如需要請添加QQ:1792099653,請備注“jackson”
第二步:解決亂碼問題, 在dispatcher-servlet.xml中配置 如下代碼
<!--json格式解決亂碼問題--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
第三步:編寫工具類 utils工具類:避免代碼的復用
import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import java.io.IOException; import java.text.SimpleDateFormat; public class utiles { public static String getJson(Object object){ return getJson(object, "yyyy-MM-dd HH:mm:ss"); } public static String getJson(Object obj, String dateformat){ ObjectMapper mapper = new ObjectMapper(); // 自定義日期格式 mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); SimpleDateFormat sdf = new SimpleDateFormat(dateformat); mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(obj); } catch (IOException e) { e.printStackTrace(); } return null; } }
第四步:編寫Controller文件,其中有個自行創建的User實體類
User實體類代碼
public class User { private String name; private int age; private int id; public User(){} public User(String name, int age, int id) { this.name = name; this.age = age; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
Controller代碼
import com.springmvc.app.dao.User; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.springmvc.app.utils.utiles; //@Controller @RestController public class UserController { @RequestMapping("/json1") // @ResponseBody //他就不會走視圖解析器,會直接返回一個字符串 public String json1() throws IOException { //創建一個對象 User user = new User("劉洋銘", 15, 1); return utiles.getJson(user); } @RequestMapping("json2") public String json2() throws IOException { //創建一個集合 List<User> userList = new ArrayList<User>(); //創建四個對象 User user1 = new User("劉洋銘1", 15, 1); User user2 = new User("劉洋銘2", 15, 1); User user3 = new User("劉洋銘3", 15, 1); User user4 = new User("劉洋銘4", 15, 1); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); return utiles.getJson(userList); } @RequestMapping("json3") public String json3() throws IOException { Date date = new Date(); return utiles.getJson(date); } }
下面是我個人的項目代碼 結構 視圖,讓大家少走彎路
以上就是全部步驟,希望能幫到各位