SpringMVC Lesson (json conversion)

SpringMVC Lesson

Returns the type of object data is converted into JSON format

Three ways:

First, the manual conversion (generally do not)

@ResponseBody
@RequestMapping("/json")// 将响应内容直接写入响应体中,而不是通过viewResolver去找视图
public String json(){
    Student student = new Student();
    student.setAge(16);
    student.setSname("gg");
    return JSON.toJSONString(student);
}

Second, the use-dependent jackson

<!--第一步:添加依赖-->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.7</version>
</dependency>

<!--第二步:在dispatcher-servlet.xml中开启MVC注解支持-->
<mvc:annotation-driven />
    
<!--第三步:转换-->
@ResponseBody
@RequestMapping("/test/google")
public Student test(){
    Student student = new Student();
    student.setAge(15);
    student.setSname("ff");
    return student;
}

Third, the use of fast-json dependent

<!--第一步:添加依赖-->
<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.57</version>
    </dependency>
    
<!--第二步:在dispatcher-servlet.xml中配置-->    
<mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
                <property name="fastJsonConfig">
                    <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
                        <property name="dateFormat" value="yyyy-MM-dd HH-mm-ss"/>
                    </bean>
                </property>
                <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>
    
<!--第三步:转换-->
@ResponseBody
@RequestMapping("/test/google")
public Student test(){
    Student student = new Student();
    student.setAge(15);
    student.setSname("ff");
    return student;
}        

Guess you like

Origin blog.csdn.net/csdn_hmt/article/details/94546310