Spring MVC json基础工具类
·
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>
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)