package com.shiryu;
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 JsonTest {
@SuppressWarnings("unchecked")
public static void main(String args[]){
//list集合转换为json代码
List list = new ArrayList();
list.add("girl");
list.add("boy");
JSONArray ja = JSONArray.fromObject(list);
System.out.println(ja);
// Map集合转换成json代码
Map map = new HashMap();
map.put("name", "kava");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("array", new String[]{"a","b"});
map.put("func", "function(){return 3;}");
JSONObject jo = JSONObject.fromObject(map);
System.out.println(jo);
//Bean转换成json代码
JSONObject jsonBean = JSONObject.fromObject(new UserBean("kava","shanghai","88765687"));
System.out.println(jsonBean);
//一般数据转换为json代码
JSONArray ja2 = JSONArray.fromObject("['json','shiryu','kava']");
System.out.println(ja2);
//一组beans转换为json代码
List list2 = new ArrayList();
UserBean u1 = new UserBean("shiryu","shanghai","6666");
UserBean u2 = new UserBean("tina","guangzhou","5587");
list2.add(u1);
list2.add(u2);
JSONArray ja3 = JSONArray.fromObject(list2);
System.out.println(ja3);
}
}
UserBean.java 代码如下:
package com.shiryu;
public class UserBean {
private String username;
private String city;
private String tel;
public UserBean() {
}
public UserBean(String username,String city,String tel) {
this.username=username;
this.city = city;
this.tel = tel;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
最后控制台结果如下:
["girl","boy"]
{"func":function(){return 3;},"int":1,"bool":true,"name":"kava","array":["a","b"]}
{"city":"shanghai","tel":"88765687","username":"kava"}
["json","shiryu","kava"]
[{"city":"shanghai","tel":"6666","username":"shiryu"},{"city":"guangzhou","tel":"5587","username":"tina"}]
也可将json数据转为java数据
StringToJson.java
package com.shiryu;
import net.sf.json.JSONObject;
public class StringToJson {
public static void main(String args[]){
String json = "{name=\"kava\",bool:true,int:1,double:2.2,func:function(a){return a;},array:[1,2]}";
// JSONObject.fromString(json)是另一种方式
JSONObject jsonObject = JSONObject.fromObject(json);
Object bean = JSONObject.toBean(jsonObject);
String name = jsonObject.getString("name");
System.out.print(name+"--"+bean.toString());
}
}