java bean 转json 串,终于找到了一篇能看懂的如何把javabean转换成json字符串的文章,嘿嘿,分享一下!...
學會了在j2ee中使用ajax后,有時候從服務(wù)器返回客戶端的數(shù)據(jù)是對象,自己手動拼湊
json字符串容易出錯,通過谷歌知道了json-lib這個類庫,方便的支持java中對象到j(luò)son字符串的轉(zhuǎn)化。
看source-forge的json-lib介紹說,需要
jakarta commons-lang 2.4
jakarta commons-beanutils 1.7.0
jakarta commons-collections 3.2
jakarta commons-logging 1.1.1
ezmorph 1.0.6
這些jar包的支持,下載下來試了一把,挺好用的,寫出來,與大家分享。
代碼如下:
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 Test {
public static void main(String[] args) {
//當是對象的時候
Student student = new Student();
student.setAge(18);
student.setName("zhangsan");
student.setSex("male");
JSONObject jsonObject = JSONObject.fromObject(student);
System.out.println(jsonObject);//輸出{"age":18,"name":"zhangsan","sex":"male"}
//當是數(shù)組或list的時候
Student[] stus = new Student[5];
List stuList = new ArrayList();
for (int i = 0; i < stus.length; i++) {
stus[i] = new Student();
stus[i].setAge(i*10+8);
stus[i].setName("zhang"+i);
stus[i].setSex("male");
//添加到list,一會兒用
stuList.add(stus[i]);
}
JSONArray jsonArray = JSONArray.fromObject(stus);
System.out.println(jsonArray);//和下面打印的結(jié)果相同
//結(jié)果:[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","sex":"male"},{"age":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex":"male"},{"age":48,"name":"zhang4","sex":"male"}]
JSONArray jsonArrayFromList = JSONArray.fromObject(stuList);
System.out.println(jsonArrayFromList);//和上面打印的結(jié)果相同
//當既有對象又有數(shù)組的時候
Map map = new HashMap();
Teacher teacher = new Teacher();
teacher.setAge(30);
teacher.setName("laoshi");
teacher.setSex("male");
map.put("teacher", teacher);
map.put("student", stuList);
JSONObject jsonObjectFromMap = JSONObject.fromObject(map);
System.out.println(jsonObjectFromMap);
//結(jié)果:
//{"student":[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","sex":"male"},{"age":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex":"male"},{"age":48,"name":"zhang4","sex":"male"}],"teacher":{"age":30,"name":"laoshi","sex":"male"}}
}
}
總結(jié)
以上是生活随笔為你收集整理的java bean 转json 串,终于找到了一篇能看懂的如何把javabean转换成json字符串的文章,嘿嘿,分享一下!...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MBT-2000主战坦克
- 下一篇: 山东立夏饭的寓意