1. List集合转换成json代码
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );
2. Map集合转换成json代码
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);
3. Bean转换成json代码
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
4. 数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5. 一般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );
实例代码:
public static void main(String[] args) {
Map map=new HashMap();
map.put("我","是");
map.put("好","孩");
map.put("子","呀");
JSONObject json = JSONObject.fromObject(map);
System.out.println(json); }
输出的結果 {"我":"是","好":"孩","子":"呀"}
toBean();
首先一个javabean对象
public class Student {
private int id ;
private String name;
private int age;
/*各属性的get和set方法*/
//重写toString方法
public String toString(){ //System.out时自动调用
return this.id + ", " + this.name + ", " + this.age; } }
然后测试toBean方法的类 import net.sf.json.JSONObject;
public class ToBeanTest {
public static void main(String[] args) {
String json = "{id:'1001',name:'张三',age:'22'}";
Student stu = new Student();
JSONObject obj = JSONObject.fromObject(json);
stu = (Student)JSONObject.toBean(obj, Student.class);
System.out.println(stu); }
}
输出结果为1001, 张三, 22
二、 JSON 使用须要用的JAR包:
commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar
三 使用JSON中的JSONObject: 1.创建一个JSONObject对象,并使用put();方法添加元素: 首先我们创建一个User对象以备后用:
public class User {
private int id;
private String name;
private String pwd;
private String sex;
//get,set方法
@Override
//重写他的toString方法 public String toString() {
return this.name+"--"+this.pwd+"--"+this.sex;
}
}
例子如下:
import net.sf.json.JSONObject;
public class TestJson {
private static JSONObject json = null;
public static void main(String[] args) {
json = new JSONObject();
json.put("id","1");
json.put("name","张三");
json.put("pwd","123456");
System.out.println(json);
}
}
运行:
C:\java>java TestJson {"id":"1","name":"张三","pwd":"123456"}
通过这段代码我们就能很清淅的看到他的添加元素和map集合方式一样。
现在我们要将这个json对象放进一个JAVABEAN的User对象怎么弄呢?很简单
我们须要在 TestJson 类中的主方法中加入(放在System.out.println(json)这句话后面)
User user = new User();
//json.getString("id")就是通过他的KEY值取得对应的value值
user.setId(Integer.parseInt(json.getString("id")));
user.setName(json.getString("name"));
user.setPwd(json.getString("pwd"));
System.out.println(user);
这样我们就把json这个对象里的值放进user对象里面了。 运行:
C:\java>java TestJson {"id":"1","name":"张三","pwd":"123456"} 张三--123456--null
json添加元素除了用put();方法之外还可以用element();如:json.element("11", "222");
2.创建一个JSONArray对象,并添加元素:
JSONArray添加元素和list集合一样,当然取值也很像,代码如下
import net.sf.json.*; public class TestJson1 { private static JSONObject json = null; private static JSONArray jsonArray = null; public static void main(String[] args) { jsonArray = new JSONArray (); jsonArray.add(0, "张三"); jsonArray.add(1, "李四"); jsonArray.add(2, "王五"); jsonArray.add(3, "小三"); System.out.println(jsonArray); System.out.println(jsonArray.get(1)); } }
输出结果为: ["张三","李四","王五","小三"] 李四
注:json的基本格式这些网上很多,就不多说了,我们只须记住一句话就行了:[]表示数组,{}表示对象就完了!
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); list.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()); } 自定义封装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); } }
//json中包含数组(集合)
JSONObject o = json.getJSONObject("data");
Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("homeConsumHis", HomeConsumHis.class);
classMap.put("monthConsumes", MonthConsumes.class);
PersonReportBean bean = (PersonReportBean) JSONObject.toBean(o,
PersonReportBean.class, classMap);
--实体类
public class PersonReportBean {
private List<HomeConsumHis> homeConsumHis ; // 家庭消费历史
private String name ; // 姓名
private List<MonthConsumes> monthConsumes ; // 月消费
/*get set 方法*/
}
JSONArray jsonarray = json.getJSONArray("cardConfirms");//数组类型 "cardConfirms":[{"message":"0001","name":"吴周","card":"622658000850","result":"0"},{"message":"0001","name":"吴周","card":"623668200000065","result":"0"}]
List<YinliankaYanzheng> list = (List<YinliankaYanzheng>) JSONArray .toCollection(jsonarray, YinliankaYanzheng.class);
部分摘自:JSONObject.fromObject(map)(JSON与JAVA数据的转换)
http://www.java3z.com/cwbwebhome/article/article20/200033.html?id=4858