Spring MVC json基础工具类
来源:互联网 发布:js按钮current trigger 编辑:程序博客网 时间:2024/06/13 21:17
public class JsonUtil { /** * 将Java对象转化为JSON字符串 * * @param obj * @return * @throws IOException */ public static String getJSON(Object obj) throws IOException { if (null == obj) { return ""; } ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); String jsonStr = mapper.writeValueAsString(obj); return jsonStr; } /** * 将JSON字符串转化为Java对象 * * @return * @throws IOException */ @SuppressWarnings("unchecked") public static <T> T getObj(String json, TypeReference<T> ref) throws IOException { if (null == json || json.length() == 0) { return null; } ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); return (T) mapper.readValue(json, ref); } public static Object getObj(String json, Class pojoClass) throws Exception { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, pojoClass); } public static void main(String[] args) throws Exception {// Dept dept=new Dept();// dept.setId(1230);// dept.setName("abcd");// String json=getJSON(dept);// System.out.println(json); String json = "{\"name\":\"abcd\",\"id\":1230}"; Dept dept = (Dept)getObj(json, Dept.class); System.out.println(dept.getId()); System.out.println(dept.getName()); }}
依赖jar包<!-- Jackson Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
@ReponseBody可能需要的转换器配置
<bean id="contentNegotiationManagerFactoryBean" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <!--是否支持后缀匹配--> <property name="favorPathExtension" value="false"/> <!--是否支持参数匹配--> <property name="favorParameter" value="false"/> <!--是否accept-header匹配--> <property name="ignoreAcceptHeader" value="false"/> <property name="mediaTypes"> <map> <!--表示.json结尾的请求返回json--> <entry key="json" value="application/json"/> <!--表示.xml结尾的返回xml--> <entry key="xml" value="application/xml"/> </map> </property> </bean>
阅读全文
1 0
- Spring MVC json基础工具类
- spring mvc 输出 json
- spring mvc json
- spring mvc json
- Spring MVC返回JSON
- Spring MVC JSON配置
- Spring MVC +JSON
- spring mvc整合json
- spring mvc json
- spring MVC返回JSON
- spring MVC 返回json
- spring mvc处理json
- Spring Mvc 输出 Json
- spring mvc整合json
- Spring mvc json 乱码
- spring mvc Json转换
- Spring MVC JSON
- spring mvc json
- 运维 10/14.15 练习题
- sqlserver游标小实例循环列表
- TP5 在模板读出Session值
- MAVEN POM.xml 标签详解
- js定时器
- Spring MVC json基础工具类
- poj3254:Corn Fields(状压DP)
- Springboot系列:@SpringBootApplication注解
- keil C51 模拟堆栈,可重入函数调用,参数传递
- MySQL性能优化的最佳20+条经验
- python里使用正则表达式的search()函数实现指定位置搜索
- hdu1521排列问题
- 编辑距离算法(LD)详解
- JavaEE基础之冒泡排序