首先去下载json-lib的jar包
http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/
然后讲jar包放入lib目录下
产品类
public class Product { private String name;//产品名称 private String description;//产品描述 private float price; public Product() { super(); } public Product(String name, String description, float price) { super(); this.name = name; this.description = description; this.price = price; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
将对象转成Json
@Test public void test1(){ Product product = new Product("充气筒", "充气专用", 10); JSONObject json = JSONObject.fromObject(product); System.out.println(json); }
输出结果为:{"description":"充气专用","name":"充气筒","price":10}
指定json需要包含的属性
@Test public void test2(){ Product product = new Product("充气筒", "充气专用", 10); JsonConfig config = new JsonConfig(); config.setExcludes(new String[]{"name","float"}); JSONObject json = JSONObject.fromObject(product,config); System.out.println(json); }
输出结果为:{"description":"充气专用","price":10}
将数组对象转成json
@Test public void test3(){ Product[] ps = {new Product("打气筒", "打气专用", 10),new Product("袜子", "黑色的", 5)}; JSONArray json = JSONArray.fromObject(ps); System.out.println(json); }
输出结果为:[{"description":"打气专用","name":"打气筒","price":10},{"description":"黑色的","name":"袜子","price":5}]
将集合对象转成json
@Test public void test4(){ List<Product> list = new ArrayList<Product>(); list.add(new Product("充气筒", "重启专用", 10)); list.add(new Product("袜子", "黑色的", 5)); JSONArray json = JSONArray.fromObject(list); System.out.println(json); }
输出结果为:[{"description":"重启专用","name":"充气筒","price":10},{"description":"黑色的","name":"袜子","price":5}]
将Map转成json
@Test public void test5(){ Map<String,Product> map = new HashMap<String,Product>(); map.put("a", new Product("充气筒", "充气专用", 10)); map.put("b", new Product("袜子","黑色的",5)); JSONArray json = JSONArray.fromObject(map); System.out.println(json); }
输出结果为:
[{"b":{"description":"黑色的","name":"袜子","price":5},"a":{"description":"充气专用","name":"充气筒","price":10}}]