首先咱們學習json的時候第一想到的是如何將JavaBean對象轉化成Json字符串,或者怎樣將json字符串轉化成JavaBean對象。html
使用ObjectMapper objectMapper = new ObjectMapper()對象。java
直接貼代碼吧,省略了了JavaBean的代碼,json
若是不想一些屬性被轉化成json字符串的話,能夠採用如下方法忽略掉:數組
JavaBean:app
由於Ios,Android均繼承了Default類因此在輸出Ios或Android視圖的時候也會輸出Default視圖。ide
測試代碼:學習
輸出結果:測試
測試代碼:url
測試結果:spa
輸出結果:
首先自定義一個序列化類(該類不能定義成內部類,不然報錯)
而後在JavaBean屬性上加上@JsonSerialize註解
測試代碼結果:
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(""); } });
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
①將簡單的Json字符串反串行化到Map對象裏時
String turingResult = "{\"code\":302000,\"text\":\"親,已幫您找到相關新聞\"}"; ObjectMapper objectMapper = new ObjectMapper(); //當須要用集合時,必須使用TypeFactory來構造集合類型 TypeFactory typeFactory = objectMapper.getTypeFactory(); Map<String, Object> map = objectMapper.readValue(turingResult, typeFactory.constructMapType(HashMap.class, String.class, Object.class)); System.out.println(map);
②將Json數組反串行化到List集合裏
String turingResult = "[{\"article\":\"工信部:今年將大幅提網速降手機流量費\",\"source\":\"網易新聞\",\"icon\":\"\",\"detailurl\":\"http://news.163.com/15/0416/03/AN9SORGH0001124J.html\"},{\"article\":\"北京最強沙塵暴午後襲滬 當地叫停廣場舞\",\"source\":\"網易新聞\",\"icon\":\"\",\"detailurl\":\"http://news.163.com/15/0416/14/ANB2VKVC00011229.html\"},{\"article\":\"公安部:小客車駕照年內試點自學直考\",\"source\":\"網易新聞\",\"icon\":\"\",\"detailurl\":\"http://news.163.com/15/0416/01/AN9MM7CK00014AED.html\"}]"; ObjectMapper objectMapper = new ObjectMapper(); //當須要用集合時,必須使用TypeFactory來構造集合類型 TypeFactory typeFactory = objectMapper.getTypeFactory(); List<Map<String, Object>> list = objectMapper.readValue(turingResult, typeFactory .constructCollectionType(ArrayList.class, typeFactory.constructMapType( HashMap.class, String.class, String.class))); System.out.println(list);