日期:2014-05-16 浏览次数:20447 次
public class Product { private String id; private int barcode; private double price; private boolean expired; public Product() { } public Product(String id, int barcode, double price, boolean expired) { this.id = id; this.barcode = barcode; this.price = price; this.expired = expired; } // getters and setters ... }
public class Staff { private String id; private String name; private Department department; public Staff() { } public Staff(String id, String name, Department department) { this.id = id; this.name = name; this.department = department; } // getters and setters ... } public class Department { private String id; private String name; public Department() { } public Department(String id, String name) { this.id = id; this.name = name; } // getters and setters ... }
Product product1 = new Product("pro001", 1111111, 100.00, false); Product product2 = new Product("pro002", 2222222, 200.00, true); Product[] products = {product1, product2}; Department department1 = new Department("dept001", "Martin's department"); Staff staff1 = new Staff("staff001", "Martin", department1); Department department2 = new Department("dept001", "Flower's department"); Staff staff2 = new Staff("staff002", "Flower", department2); Staff[] staffs = {staff1, staff2};
//把单个Product对象转为JSONObject对象 JSONObject jsonProduct = JSONObject.fromObject(product1); System.out.println(jsonProduct.toString());
{"barcode":1111111,"expired":false,"id":"pro001","price":100}
//把前面的把JSONObject对象转回单个Product对象 Product productTest = (Product) JSONObject.toBean(jsonProduct, Product.class);
//定义一个Map类型的classMap,其key为成员的变量名,其value为成员的类型名 HashMap<String, Object> classMap = new HashMap<String, Object>(); classMap.put("department", Department.class); //把Staff对象转为JsonObject JSONObject jsonStaff = JSONObject.fromObject(staff1); System.out.println(jsonStaff.toString());
{"department":{"id":"dept001","name":"Martin's department"},"id":"staff001","name":"Martin"}
//再把JsonObject转回Staff Staff staffTest = (Staff) JSONObject.toBean(jsonStaff, Staff.class, classMap);
JSONArray jsonProducts = JSONArra