Jackson的JSON處理-ObjectMapper

來源:互聯網
上載者:User

標籤:jar   mapper   blog   add   size   keyset   item   val   pwd   

Jackson可以輕鬆的將Java對象轉換成json對象和xml文檔,同樣也可以將json、xml轉換成Java對象準備工作1、 下載依賴庫jar包Jackson的jar all    jackson-all-1.7.6.jar因為下面的程式是用junit測試案例啟動並執行,所以還得添加junit的jar包如果你需要轉換xml,那麼還需要stax2-api.jar2、 測試類別基本代碼如下
public class Jackson {       public  static JsonGenerator jsonGenerator = null;      private static ObjectMapper mapper = new ObjectMapper();      public static void main(String[] args) {          Student student = new Student();          student.setIsstudent(true);          student.setUid(1000);          student.setUname("xiao liao");          student.setUpwd("123");          student.setNumber(12);                    Map<String, Student> stuMap = new HashMap<String, Student>();          stuMap.put("1", student);          stuMap.put("2", student);                    List<Object> stuList = new ArrayList<Object>();          List<Student> stuList1 = new ArrayList<Student>();          stuList1.add(student);          student=  new  Student();          student.setIsstudent(false);          student.setUid(200);          student.setUname("xiao mi");          stuList1.add(student);                    stuList.add(student);          stuList.add("xiao xin");          stuList.add("xiao er");          stuList.add(stuMap);                    //readJson2List();          try {              //readJson2Array();              //writeArray2Json(array);              //writeJson2List();              //writeEntity2Json(student);              writeJson2Entity();              //writeMap2Json(stuMap);              //writeList2Json(stuList1);             } catch (IOException e) {e.printStackTrace();}      }      public static void writeEntity2Json(Object object) throws IOException {          mapper.writeValue( new File("D:\\testjson1\\lib\\aa.txt"),object );          mapper.writeValue( System.out,object );       }      public static void writeArray2Json(Object object) throws IOException {           // writeValue具有和writeObject相同的功能           mapper.writeValue( new File("D:\\testjson1\\lib\\aa.txt"),object );           mapper.writeValue(System.out,object );           }           public static void writeMap2Json(Object object) throws IOException {           System.out.println("使用ObjectMapper-----------");           // writeValue具有和writeObject相同的功能           System.out.println("==>"+mapper.writeValueAsString(object));           mapper.writeValue( new File("D:\\testjson1\\lib\\aamap.txt"),object );           mapper.writeValue( System.out , object );       }       public static void writeList2Json(Object object) throws IOException {           System.out.println("==>"+mapper.writeValueAsString(object));           mapper.writeValue( new File("D:\\testjson1\\lib\\aamap.txt"),object );           mapper.writeValue( System.out , object );       }        public static void writeJson2Entity() throws IOException {           System.out.println("json串轉換成entity-------------");  //       File file = new File("D:\\testjson1\\lib\\aa.txt");  //       FileInputStream inputStream = new FileInputStream(file);  //       Student student = mapper.readValue(inputStream,Student.class);  //       System.out.println(student.toString());          //mapper.defaultPrettyPrintingWriter().writeValueAsString(value);                 String json = "{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true}";           Student student1 = mapper.readValue(json,Student.class);           System.out.println("json2:"+student1.toString());       }       public static void writeJson2List() throws IOException {           System.out.println("json串轉換成entity-------------");           File file = new File("D:\\testjson1\\lib\\aa.txt");           FileInputStream inputStream = new FileInputStream(file);           Student student = mapper.readValue(inputStream,Student.class);           System.out.println(student.toString());                      String json= "[{\"uid\":1000,\"uname\":\"xiao liao\",\"upwd\":\"123\",\"number\":12.0,\"isstudent\":true},
{\"uid\":200,\"uname\":\"xiao mi\",\"upwd\":null,\"number\":0.0,\"isstudent\":false}]"; List<LinkedHashMap<String, Object>> s= mapper.readValue(json,List.class); for (int i = 0; i < s.size(); i++) { LinkedHashMap<String, Object> link = s.get(i); Set<String> key = link.keySet(); for (Iterator iterator = key.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); System.out.println(string+"==>"+link.get(string)); } System.out.println("json:"+i+""+s.get(i).toString()); } } //JSON轉換為List對象 public static void readJson2List() { String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"}," + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]"; try { List<LinkedHashMap<String, Object>> list = mapper.readValue( json, List.class); System.out.println(list.size()); for (int i = 0; i < list.size(); i++) { Map<String, Object> map = list.get(i); Set<String> set = map.keySet(); for (Iterator<String> it = set.iterator(); it.hasNext();) { String key = it.next(); System.out.println(key + ":" + map.get(key)); } } } catch (JsonParseException e) {e.printStackTrace(); } catch (JsonMappingException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace();} } //JSON轉換為List對象 public static void readJson2Array() { String json = "[{\"uid\":1,\"uname\":\"www\",\"number\":234,\"upwd\":\"456\"}," + "{\"uid\":5,\"uname\":\"tom\",\"number\":3.44,\"upwd\":\"123\"}]"; try { Student[] students = mapper.readValue(json, Student[].class); for (Student student : students) { System.out.println(">"+student.toString()); } } catch (JsonParseException e) {e.printStackTrace(); } catch (JsonMappingException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace();} } }
列印結果 :串轉換成entity-------------json2:uid=1000,name=xiao liao,upwd=123,number=12.0,isStudent=truewriteMap2Json -----------{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},
"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}readJson2Array------------------>uid=1,name=www,upwd=456,number=234.0,isStudent=false>uid=5,name=tom,upwd=123,number=3.44,isStudent=falsewriteMap2Json -----------{"2":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true},
"1":{"uid":1000,"uname":"xiao liao","upwd":"123","number":12.0,"isstudent":true}}
public class Student {        private int uid;        private String uname;        private String upwd;        private double number;        private boolean isstudent;       getset方法}  

Jackson的JSON處理-ObjectMapper

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.