Show pageBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Basic Gson ====== ===== Add Gson Dependency ===== <code> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> </code> ===== Assumption ===== Assume we have a Company class, and a Staff class such that Company has a name, a start date, and a list of staff, and the staff has a name, and a salary field. We use the following code to create the Java objects. <code> Company company = new Company(); company.setName("ABC Company"); company.setStartDate(new Date()); Staff staff1 = new Staff(); staff1.setName("Staff 1"); staff1.setSalary(10000.0); Staff staff2 = new Staff(); staff2.setName("Staff 2"); staff2.setSalary(20000.0); Staff staff3 = new Staff(); staff3.setName("Staff 3"); staff3.setSalary(30000.0); Staff staff4 = new Staff(); staff4.setName("Staff 4"); staff4.setSalary(40000.0); List<Staff> list = new ArrayList<Staff>(); list.add(staff1); list.add(staff2); list.add(staff3); list.add(staff4); company.setStaffs(list); </code> ===== To Json ===== <code> Gson gson = new Gson(); String json = gson.toJson(company); System.out.println(json); </code> The result would be <code>{"name":"ABC Company","startDate":"Aug 13, 2019 2:39:50 PM","staffs":[{"name":"Staff 1","salary":10000.0},{"name":"Staff 2","salary":20000.0},{"name":"Staff 3","salary":30000.0},{"name":"Staff 4","salary":40000.0}]} </code> ===== From Json ===== Assume we user the output from above to create a Company object: <code>Company testCompany = gson.fromJson(json, Company.class);</code> java/basic_gson.txt Last modified: 2019/08/13 14:56by chongtin