springmvc转换json数据

1接受JSON格式数据:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>



    
    测试接收JSON格式的数据
    <%----%>
    
    
    


编号:
书名:
作者:

package controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import model.Book;
import model.Car;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Controller
@RequestMapping("/json")
public class BookController {

    @RequestMapping("/testRequestBody")
    public void setJosn(@RequestBody Book book, HttpServletResponse response) throws Exception{
        String s = JSONObject.toJSONString(book);//fastjson接受json数据
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(JSONObject.toJSONString(book));
    }

  
}

2.返回JSON格式的数据

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/18 0018
  Time: 10:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    测试返回Json格式的数据
    
    

    


编号 书名 作者

package controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import model.Book;
import model.Car;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Controller
@RequestMapping("/json")
public class BookController {



    @RequestMapping("/testResponseBody")
    public @ResponseBody Object getJson(){
        List books = new ArrayList();
        books.add(new Book("1","spring+mybatis企业应用实战","肖吉文"));
        books.add(new Book("2","Java疯狂讲义","李刚"));
        return books;
    }
}

json需要的pom.xml

  
      com.alibaba
      fastjson
      1.2.39
    



你可能感兴趣的:(springmvc转换json数据)