java方式的將java對象以及list或者map轉化為json資料 .

來源:互聯網
上載者:User
public class Test {public static void main(String[] args) {//當是對象的時候Student student = new Student();student.setAge(18);student.setName("zhangsan");student.setSex("male");JSONObject jsonObject = JSONObject.fromObject(student);System.out.println(jsonObject);//輸出{"age":18,"name":"zhangsan","sex":"male"}//當是數組或list的時候Student[] stus = new Student[5];List<Student> stuList = new ArrayList<Student>();for (int i = 0; i < stus.length; i++) {stus[i] = new Student();stus[i].setAge(i*10+8);stus[i].setName("zhang"+i);stus[i].setSex("male");//添加到list,一會兒用stuList.add(stus[i]);}JSONArray jsonArray = JSONArray.fromObject(stus);System.out.println(jsonArray);//和下面列印的結果相同//結果:[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","sex":"male"},{"age":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex":"male"},{"age":48,"name":"zhang4","sex":"male"}]JSONArray jsonArrayFromList = JSONArray.fromObject(stuList);System.out.println(jsonArrayFromList);//和上面列印的結果相同//當既有對象又有數組的時候Map<String,Object> map = new HashMap<String,Object>();Teacher teacher = new Teacher();teacher.setAge(30);teacher.setName("laoshi");teacher.setSex("male");map.put("teacher", teacher);map.put("student", stuList);JSONObject jsonObjectFromMap = JSONObject.fromObject(map);System.out.println(jsonObjectFromMap);//結果://{"student":[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","sex":"male"},{"age":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex":"male"},{"age":48,"name":"zhang4","sex":"male"}],"teacher":{"age":30,"name":"laoshi","sex":"male"}}}}

聯繫我們

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