关于包:
json-lib-2.4-jdk15
ezmorph-1.0.6
commons-lang-2.6
commons-logging-1.1.3
commons-beanutils-1.9.1
commons-collections-3.2.1
不能使用lang3,collection4
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class Test {
public static void main(String[] args) {
/**
* 将 Array 解析成 Json 串
*/
String[] str = { "Jack", "Tom", "90", "true" };
JSONArray json = JSONArray.fromObject(str);
System.out.println(json);
/**
* 对象数组,注意数字和布尔值
*/
Object[] o = { "北京", "上海", 89, true, 90.87 };
json = JSONArray.fromObject(o);
System.out.println(json);
/**
* 使用集合类
*/
List<String> list = new ArrayList<String>();
list.add("Jack");
list.add("Rose");
json = JSONArray.fromObject(list);
System.out.println(json);
/**
* 使用 set 集合
*/
Set<Object> set = new HashSet<Object>();
set.add("Hello");
set.add(true);
set.add(99);
json = JSONArray.fromObject(set);
System.out.println(json);
/**
* 解析 HashMap
*/
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Tom");
map.put("age", 33);
JSONObject jsonObject = JSONObject.fromObject(map);
System.out.println(jsonObject);
/**
* 解析 JavaBean
*/
Person person = new Person("A001", "Jack");
jsonObject = JSONObject.fromObject(person);
System.out.println(jsonObject);
/**
* 解析嵌套的对象
*/
map.put("person", person);
jsonObject = JSONObject.fromObject(map);
System.out.println(jsonObject);
/**
* 使用 JsonConfig 过虑属性:适用于 JavaBean/Map
*/
JsonConfig config = new JsonConfig();
config.setExcludes(new String[] { "name" }); // 指定在转换时不包含哪些属性
person = new Person("A001", "Jack");
jsonObject = JSONObject.fromObject(person, config); // 在转换时传入之前的配置对象
System.out.println(jsonObject);
/**
* 将 Json 串转换成 Array
*/
JSONArray jsonArray = JSONArray.fromObject("[89,90,99]");
Object array = JSONArray.toArray(jsonArray);
System.out.println(array);
System.out.println(Arrays.asList((Object[]) array));
/**
* 将 Json 形式的字符串转换为 Map
*/
String str2 = "{\"name\":\"Tom\",\"age\":90}";
jsonObject = JSONObject.fromObject(str2);
Map<String, Object> map2 = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
System.out.println(map2);
/**
* 将 Json 形式的字符串转换为 JavaBean
*/
str2 = "{\"id\":\"A001\",\"name\":\"Jack\"}";
jsonObject = JSONObject.fromObject(str2);
System.out.println(jsonObject);
person = (Person) JSONObject.toBean(jsonObject, Person.class);
System.out.println(person);
}
}
public class Person {
private String id;
private String name;
public Person(){
}
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}