基于spring mvc的框架,要求返回json、xml格式的数据,
1、开始用的方法是 把数据对象用 fastjosn工具包转成json字符 再往页面写, 这种方式对象中字段为null的 就不会表现在json字符串中,形式如下:
{"msg":"请传入合法的op参数","result":"false"}
2、方法二用的是spring mvc的 org.springframework.web.servlet.view.json.MappingJacksonJsonView ,其不管你对象中字段是否为null 全部表现在json字符串中,如下:
{"msgTip":{"result":"fasle","userId":null,"msg":"请传入合法的op参数","sightId":null,"pathId":null}} 另外spring mvc 还能自动转成xml org.springframework.web.servlet.view.xml.MarshallingView 3、配置如下 <!-- 视图解析器,根据视图的名称new ModelAndView(name),在配置文件查找对应的bean配置 --> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"> <property name="order" value="1"/> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> </bean> <!--json view--> <bean id="testJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> <property name="encoding"> <value type="org.codehaus.jackson.JsonEncoding">UTF8</value> </property> <property name="contentType" value="application/json;charset=UTF-8"/> </bean><!--xml view--><bean name="testjaxb2MarshallingView" class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<array>
<value>com.gvitech.biz.domain.MsgTip</value>
</array>
</property>
</bean>
</constructor-arg>
</bean>
4、调用:
MsgTip tip = new MsgTip("fasle","请传入合法的op参数");
mav = new ModelAndView("testJsonView"); //对应bean id
mav.addObject(tip);
return mav;