添加 jar 包支持
commons-beanutils-1.8.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
编写工具类
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonUtils {
public static <T> T toObject(String data, Class<T> clazz) {
return (T) JSONObject.toBean(JSONObject.fromObject(data), clazz);
}
public static String toJson(Object object) {
return JSONObject.fromObject(object).toString();
}
public static String toJsonByList(Object object) {
return JSONArray.fromObject(object).toString();
}
public static <T> List<T> toList(String data, Class<T> clazz) {
return (List<T>) JSONArray.toCollection(JSONArray.fromObject(data), clazz);
}
}
测试代码
import java.util.ArrayList;
import java.util.List;
import model.Person;
import org.junit.Test;
import util.JsonUtils;
public class JsonTest {
/**
* Object ---> JSON
*/
@Test
public void testObjectToJson() {
Person p = new Person();
p.setName("张三");
p.setAge("18");
p.setAddress("郑州");
String result = JsonUtils.toJson(p);
System.out.println(result);
}
/**
* JSON ---> Object
*/
@Test
public void testJsonToObject() {
String data = "{\"address\":\"郑州\",\"age\":\"18\",\"name\":\"张三\"}";
Person p = JsonUtils.toObject(data, Person.class);
System.out.println(p);
}
/**
* List ---> JSON
*/
@Test
public void testListToJson() {
Person p1 = new Person();
p1.setName("张三");
p1.setAge("18");
p1.setAddress("郑州");
Person p2 = new Person();
p2.setName("李四");
p2.setAge("20");
p2.setAddress("北京");
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
String result = JsonUtils.toJsonByList(list);
System.out.println(result);
}
/**
* JSON ---> List
*/
@Test
public void testJsonToList() {
String data = "[{\"address\":\"郑州\",\"age\":\"18\",\"name\":\"张三\"},{\"address\":\"北京\",\"age\":\"20\",\"name\":\"李四\"}]";
List<Person> list = JsonUtils.toList(data, Person.class);
for (Person person : list) {
System.out.println(person);
}
}
}