spring mvc json乱码问题

来源:互联网 发布:大智慧数据接口 编辑:程序博客网 时间:2024/05/17 09:19
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


import com.fasterxml.jackson.databind.ObjectMapper; //Jsckson JSON Processer


import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.nio.charset.Charset;

@Controller
public class HomeController {
    @RequestMapping(value="/Home/writeJson", method=RequestMethod.GET)
    public void writeJson(HttpServletResponse response)
    {
        ObjectMapper mapper = new ObjectMapper();


        HashMap<String,String> map = new HashMap<String,String>();
        map.put("1","张三");
        map.put("2","李四");
        map.put("3","王五");
        map.put("4", "Jackson");


        String json = "";


        try
        {
            json = mapper.writeValueAsString(map);
            System.out.println(json);


            //方案二
            ServletOutputStream os = response.getOutputStream(); //获取输出流
            os.write(json.getBytes(Charset.forName("GBK"))); //将json数据写入流中
            os.flush();



            //方案一
            response.setCharacterEncoding("UTF-8"); //设置编码格式
            response.setContentType("text/html");   //设置数据格式
            PrintWriter out = response.getWriter(); //获取写入对象
            out.print(json); //将json数据写入流中
            out.flush();

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


        //return "home";
    }

}





注解配置!!!!!!!!!!!!!!!!!!!!

 

@RequestMapping(value="/Home/writeJson", method=RequestMethod.GET, produces = "text/html;charset=UTF-8")
@ResponseBody

public Object writeJson(HttpServletResponse response)
{
        ObjectMapper mapper = new ObjectMapper();


        HashMap<String,String> map = new HashMap<String,String>();
        map.put("1","张三");
        map.put("2","李四");
        map.put("3","王五");
        map.put("4", "Jackson");


        String json = "";


        try
        {
            json = mapper.writeValueAsString(map);
            System.out.println(json);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


        return json;
}

0 0
原创粉丝点击