首先需要使用如下的jar包:
1.commons-lang.jar
2.commons-beanutils.jar
3.commons-collections.jar
4.commons-logging.jar
5.ezmorph.jar
6.json-lib-2.2.2-jdk15.jar
其次给出一个测试
例子:
////////////////////////////
给出一个常见的JavaBean
public
class BookInfo {
private String name;
private float price;
private int num;
public BookInfo(){
}
public BookInfo(String name,float price,int num){
this.name=name;
this.price=price;
this.num=num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
///////////////////////////
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.
JSONArray;
import net.sf.json.
JSONObject;
public class TestJSON {
public TestJSON(){
}
public static void main(String[] args) {
BookInfo book=new BookInfo();
book.setName("java");
book.setNum(10);
book.setPrice(1.5f);
System.out.println(JSONArray.fromObject(book).toString());
BookInfo book2=new BookInfo("C#",31.9f,30);
BookInfo book3=new BookInfo("C#",32.9f,30);
BookInfo book4=new BookInfo("C#",33.9f,30);
BookInfo book5=new BookInfo("C#",35.9f,30);
BookInfo book6=new BookInfo("C#",44.9f,30);
List<BookInfo>list=new ArrayList<BookInfo>();
list.add(book6);list.add(book5);list.add(book4);list.add(book3);list.add(book2);
// 集合list转成json数据
JSONArray array=JSONArray.fromObject(list);
System.out.println("JSONArray格式"+array.size()+"个,内容:"+array.toString());
System.out.println("第2个内容是"+array.get(2).toString()+"从第0个开始");
// map转成json代码
Map map=new HashMap();
map.put("name", "书籍");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] {"a","b"});
map.put("fun", "
function(i){return this.arr[i];}");
JSONObject json=JSONObject.fromObject(map);
System.out.println("JSONObject格式:"+json.toString());
System.out.println(json.get("name")+":"+json.get("fun"));
// 数据转成JSON
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
System.out.println(jsonArray1.size());
System.out.println("Bean转换成json代码 ");
System.out.println(jsonArray1.toString());
// 一般数据转成JSON
System.out.println(JSONArray.fromObject("['json','is','easy']"));
System.out.println("第0个是:"+JSONArray.fromObject("['json','is','easy']").get(0));
}
}