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>