Jackson將json字串轉換成泛型List

來源:互聯網
上載者:User

標籤:style   http   io   color   os   ar   使用   java   sp   

 Jackson,我感覺是在Java與Json之間相互轉換的最快速的架構,當然Google的Gson也很不錯,但是參照網上有人的效能測試,看起來還是Jackson比較快一點

    Jackson處理一般的JavaBean和Json之間的轉換隻要使用ObjectMapper 對象的readValue和writeValueAsString兩個方法就能實現。但是如果要轉換複雜類型Collection如 List<YourBean>,那麼就需要先還原序列化複雜類型 為泛型的Collection Type。

如果是ArrayList<YourBean>那麼使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);

如果是HashMap<String,YourBean>那麼 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);

public final ObjectMapper mapper = new ObjectMapper(); 

     

    public static void main(String[] args) throws Exception{  

        JavaType javaType = getCollectionType(ArrayList.class, YourBean.class); 

        List<YourBean> lst =  (List<YourBean>)mapper.readValue(jsonString, javaType); 

    }   

       /**   

        * 擷取泛型的Collection Type  

        * @param collectionClass 泛型的Collection   

        * @param elementClasses 元素類   

        * @return JavaType Java類型   

        * @since 1.0   

        */   

    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {   

        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);   

    }


Jackson將json字串轉換成泛型List

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.