ps:看这篇博客之前首先要引入工具包json-lib-2.2.2-jdk15.jar
资源链接:百度云:链接:https://pan.baidu.com/s/1o9k7PSu 密码:00lj
一、从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); list.add(book2); JSONArray arry=JSONArray.fromObject(list); System.out.println(arry.toString()); //结果如下: [{"name":"Java","price":52.3},{"name":"C","price":42.3}]
二、从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")); }
三、从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()); }
三、自定义封装JSON操作的类
package com.util; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonHelper { //从普通的Bean转换为字符串 public static String getJson(Object o){ JSONObject jo=JSONObject.fromObject(o); return jo.toString(); } //从Java的列表转换为字符串 public static String getJson(List list){ JSONArray ja=JSONArray.fromObject(list); return ja.toString(); } //从Java对象数组转换为字符串 public static String getJson(Object[] arry){ JSONArray ja=JSONArray.fromObject(arry); return ja.toString(); } //从json格式的字符串转换为Map对象 public static Map getObject(String s){ return JSONObject.fromObject(s); } //从json格式的字符串转换为List数组 public static List getArray(String s){ return JSONArray.fromObject(s); } //从json格式的字符串转换为某个Bean public static Object getObject(String s,Class cls){ JSONObject jo=JSONObject.fromObject(s); return JSONObject.toBean(jo, cls); } //从json格式的字符串转换为某类对象的数组 public static Object getArray(String s,Class cls){ JSONArray ja=JSONArray.fromObject(s); return JSONArray.toArray(ja, cls); } }