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 getObj(String json, TypeReference 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包

com.fasterxml.jackson.core
jackson-databind
2.7.4

@ReponseBody可能需要的转换器配置

    <bean id="contentNegotiationManagerFactoryBean"
          class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    
    <property name="favorPathExtension" value="false"/>
    
    <property name="favorParameter" value="false"/>
    
    <property name="ignoreAcceptHeader" value="false"/>
    <property name="mediaTypes">
        <map>
            
            <entry key="json" value="application/json"/>
            
            <entry key="xml" value="application/xml"/>
        map>

    property>
    bean>

你可能感兴趣的:(工具类)