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);
譬如,我有如下一個Config.java對象
1 public class Config { 2 private String name; 3 private String value; 4 5 public Config() { 6 } 7 8 public Config(String name, String value) { 9 this.name = name; 10 this.value = value; 11 } 12 }
如果我需要將json字符串轉換為Config對象數組,即執行反序列號,則需要執行以下的方法:
1 public final ObjectMapper mapper = new ObjectMapper(); 2 3 public static void main(String[] args) throws Exception{ 4 5 String jsonString = getConfig(); //getConfig省略 6 7 //List<Config> configList = (List<Config>)jsonString 8 //上面這樣轉換是錯的,但是編譯沒有報錯,運行時才報錯 9 10 JavaType javaType = getCollectionType(ArrayList.class, Config.class); 11 List<Config> configList = mapper.readValue(jsonString, javaType); //這里不需要強制轉換 12 } 13 14 15 /** 16 * 獲取泛型的Collection Type 17 * @param collectionClass 泛型的Collection 18 * @param elementClasses 元素類 19 * @return JavaType Java類型 20 * @since 1.0 21 */ 22 public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { 23 return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); 24 }