1.
从Object到String
要先用Object构造一个JSONObject对象或者一个JSONArray对象,然后调用他的toString()方法即可。
-->1.
案例一:
Book book=new Book();
book.setName("Java");
book.setPrice(52.3f);
JSONObject object=JSONObject.fromObject(book);
System.out.println(object.toString());
-->2.
案例二:
Book book=new Book();
book.setName("Java");
book.setPrice(52.3f);
Book book2=new Book();
book2.setName("C");
book2.setPrice(42.3f);
List list=new ArrayList();
list.add(book);
ist.add(book2);
JSONArray arry=JSONArray.fromObject(list);
System.out.println(arry.toString());
//结果如下:
[{"name":"Java","price":52.3},{"name":"C","price":42.3}]
2.
从String到Object
要先用String对象构造一个JSONObject或者JSONArray对象
------>1.
案例一:
String json="{name:'Java',price:52.3}";
JSONObject object=JSONObject.fromObject(json);
System.out.println(object.get("name")+" "+object.get("price"));
-------->2.
案例二:
String json="[{name:'Java',price:52.3},{name:'C',price:42.3}]";
JSONArray array=JSONArray.fromObject(json);
for(int i=0;i<array.size();i++){
Map o=(Map)array.get(i);
System.out.println(o.get("name")+" "+o.get("price"));
}
3.
从String到Bean
------->1.
单个Bean对象
String json="{name:'Java',price:52.3}";
JSONObject object=JSONObject.fromObject(json);
Product product=(Product)JSONObject.toBean(object,Product.class);
System.out.println(product.getName()+" "+product.getPrice());
-------->2.
Bean的数组
String json="[{name:'Java',price:52.3},{name:'C',price:42.3}]";
JSONArray array=JSONArray.fromObject(json);
Product[] products=(Product[]) JSONArray.toArray(array,Product.class);
for(Product p:products){
System.out.println(p.getName()+" "+p.getPrice());
}