SpringMVC之Json的简单应用

SpringMVC之Json的简单应用

1.解决Json返回的乱码问题,可在springmvc 配置文件加入下面的。

<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-8value>
                        <value>application/json;charset=UTF-8value>
                        <value>text/plain;charset=UTF-8value>
                        <value>application/xml;charset=UTF-8value>
                    list>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>

Controller类

package com.harris.controller;

import com.alibaba.fastjson.JSON;
import com.harris.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

@RestController
public class JsonController {
     
    @RequestMapping("/j1")
    public String json1(){
     
        ArrayList<Integer> a = new ArrayList<Integer>();
        a.add(123);
        a.add(555);
        a.add(666);
        return JSON.toJSONString(a);
    }
    @RequestMapping("/j2")
    public  String json2(){
     
        return JSON.toJSONString(new User(1,"小明",19));
    }
}

运行结果

SpringMVC之Json的简单应用_第1张图片

你可能感兴趣的:(Web)