Java converts Java objects and list or map into JSON data.

Source: Internet
Author: User
Public class test {public static void main (string [] ARGs) {// student = new student (); student. setage (18); student. setname ("zhangsan"); student. setsex ("male"); jsonobject = jsonobject. fromobject (student); system. out. println (jsonobject); // output {"Age": 18, "name": "zhangsan", "sex ": "male"} // when it is an array or 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"); // Add it to the list and use stulist. add (stus [I]);} jsonarray = jsonarray. fromobject (stus); system. out. println (jsonarray); // The result is the same as the following: // result: [{"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); // The result is the same as the one printed above. // when both objects and arrays exist, Map <string, Object> map = new hashmap <string, object> (); 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); // result: // {"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 "}}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.