SSM URL接口 返回Json数组
参考了下网上经典文章,SSM模式下URL接口采用@ResponseBody注解返回Json数组有这么几种方案
第一种是@ResponseBody的注解方式,采用getJson方法解析
其中List<Song> song = songService.loadPersons(); List为获取实例的方法,songService为Service模块中的方法。
其中方法名成为Object getJson为java解析Json对象的一种方式。
测试结果
第二种是@ResponseBody的注解方式,采用HashMap 方法
采用HashMap方法时,是用了put方法。
测试结果
具体HashMap用法请百度。
注意:
在使用Json时需要在SSM项目中需要加入Json字符串的支持
在pom.xml中加入
<!-- 返回json字符串的支持-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
在spring-MVC中加入
<!-- ========================================分隔线========================================= -->
<!-- 配置json转换器-->
<bean id="jsonMessageConverters" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- JSON视图拦截器,碰到ResponseBody会触发-->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverters"/>
</list>
</property>
</bean>