需要依赖的jar包: commons-lang.jar commons-beanutils.jar commons-collections.jar commons-logging.jar ezmorph.jar json-lib-2.2.2-jdk15.jar
首先简单地看一下JSONObject,JSONArray对象的创建以及Json字符串的解析:
[java]
view plain copypackage com.peter.jsonobj.test;
import java.util.ArrayList;
import java.util.HashMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test2 {
public static void main(String[] args) {
//JsonObject和JsonArray区别就是JsonObject是对象形式,JsonArray是数组形式
//创建JsonObject第一种方法
JSONObject jsonObject = new JSONObject();
jsonObject.put("UserName", "ZHULI");
jsonObject.put("age", "30");
jsonObject.put("workIn", "ALI");
System.out.println("jsonObject1:" + jsonObject);
//创建JsonObject第二种方法
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("UserName", "ZHULI");
hashMap.put("age", "30");
hashMap.put("workIn", "ALI");
System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));
//创建一个JsonArray方法1
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, "ZHULI");
jsonArray.add(1, "30");
jsonArray.add(2, "ALI");
System.out.println("jsonArray1:" + jsonArray);
//创建JsonArray方法2
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("ZHULI");
arrayList.add("30");
arrayList.add("ALI");
System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList));
//如果JSONArray解析一个HashMap,则会将整个对象的放进一个数组的值中
System.out.println("jsonArray FROM HASHMAP:" + JSONArray.fromObject(hashMap));
//组装一个复杂的JSONArray
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("UserName", "ZHULI");
jsonObject2.put("age", "30");
jsonObject2.put("workIn", "ALI");
jsonObject2.element("Array", arrayList);
System.out.println("jsonObject2:" + jsonObject2);
//解析JSON字符串:
String jsonString = "{\"UserName\":\"ZHULI\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"ZHULI\",\"30\",\"ALI\"]}";
//将Json字符串转为java对象
JSONObject obj = JSONObject.fromObject(jsonString);
//获取Object中的UserName
if (obj.has("UserName")) {
System.out.println("UserName:" + obj.getString("UserName"));
}
//获取ArrayObject
if (obj.has("Array")) {
JSONArray transitListArray = obj.getJSONArray("Array");
for (int i = 0; i < transitListArray.size(); i++) {
System.out.print("Array:" + transitListArray.getString(i) + " ");
}
}
}
}
结果如下:
jsonObject1:{"workIn":"ALI","age":"30","UserName":"ZHULI"}
jsonObject2:{"workIn":"ALI","age":"30","UserName":"ZHULI"}
jsonArray1:["ZHULI","30","ALI"]
jsonArray2:["ZHULI","30","ALI"]
jsonArray FROM HASHMAP:[{"workIn":"ALI","age":"30","UserName":"ZHULI"}]
jsonObject2:{"workIn":"ALI","age":"30","Array":["ZHULI","30","ALI"],"UserName":"ZHULI"}
UserName:ZHULI
Array:ZHULI Array:30 Array:ALI
由于我们涉及更多的是对象(Bean)与Json字符串之间的转换.这里我创建了我的Model类
[java]
view plain copypackage com.peter.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ClassInfo implements Serializable{
private String className;
private int classNum;
private Teacher teacher;
private List<Student> students=new ArrayList<Student>();
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public int getClassNum() {
return classNum;
}
public void setClassNum(int classNum) {
this.classNum = classNum;
}
@Override
public String toString() {
return "ClassInfo [className=" + className + ", classNum=" + classNum
+ ", teacher=" + teacher + ", students=" + students + "]";
}
}
[java]
view plain copypackage com.peter.model;
import java.io.Serializable;
import java.util.Date;
public class Student implements Serializable{
private int id;
private String name;
private Date birthDay;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
@Override
public String toString() {
return "Student [birthDay=" + birthDay + ", id=" + id + ", name="
+ name + "]";
}
}
[java]
view plain copy<pre name="code" class="java">package com.peter.model;
import java.io.Serializable;
public class Teacher implements Serializable{
private String name;
private String jabNum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJabNum() {
return jabNum;
}
public void setJabNum(String jabNum) {
this.jabNum = jabNum;
}
@Override
public String toString() {
return "Teacher [name=" + name + ", jabNum=" + jabNum + "]";
}
}
以上的model基本上能满足所有的Json字符串格式.
[java]
view plain copypackage com.peter.jsonobj.test;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;
import com.peter.model.ClassInfo;
import com.peter.model.Student;
import com.peter.model.Teacher;
public class Test {
public static void main(String[] args) {
Student student1 = new Student();
student1.setId(1);
student1.setName("李坤");
student1.setBirthDay(new Date());
// //////////////////////////////////////////////////////////
System.out.println("----------简单对象之间的转化-------------");
// 简单的bean转为json
// 默认日期:"birthDay":{"time":1445158142832,"minutes":49,"seconds":2,"hours":16,"month":9,"year":115,"timezoneOffset":-480,"day":0,"date":18}
JSONObject jso = JSONObject.fromObject(student1);
String s1 = jso.toString();
System.out.println("(默认日期)简单Bean转化为Json===" + s1);
JSONObject jso1 = JSONObject.fromObject(student1, getConfig());
s1 = jso1.toString();
System.out.println("(设置日期)简单Bean转化为Json===" + s1);
// // json转为简单Bean
JSONObject o1 = (JSONObject) JSONSerializer.toJSON(s1);
Student student = (Student) JSONObject.toBean(o1, Student.class);
System.out.println("Json转为简单Bean===" + student);
Student student2 = new Student();
student2.setId(2);
student2.setName("曹贵生");
student2.setBirthDay(new Date());
Student student3 = new Student();
student3.setId(3);
student3.setName("柳波");
student3.setBirthDay(new Date());
List<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
list.add(student3);
System.out.println("----------带泛型的List之间的转化-------------");
JSONArray jary1 = JSONArray.fromObject(list, getConfig());
// 带泛型的list转化为json
String s2 = jary1.toString();
System.out.println("带泛型的list转化为json==" + s2);
// json转为带泛型的list
// 数组
Student[] arrList = (Student[]) JSONArray.toArray(jary1, Student.class);
// 集合
@SuppressWarnings("unchecked")
List<Student> lists = JSONArray.toList(jary1, Student.class);
for (Student stu : arrList) {
System.out.println(stu.getName());
}
for (Student stu : lists) {
System.out.println(stu.getName());
}
//
Teacher t = new Teacher();
t.setJabNum("t101");
t.setName("lijun");
ClassInfo ci = new ClassInfo();
ci.setClassName("cna");
ci.setClassNum(101);
ci.setStudents(list);
ci.setTeacher(t);
JSONObject clajso = JSONObject.fromObject(ci, getConfig());
String c = clajso.toString();
System.out.println("ci to json //////////////");
System.out.println(c);
System.out.println("json to ci //////////");
JSONObject o2 = (JSONObject) JSONSerializer.toJSON(c);
ClassInfo cijson = (ClassInfo) JSONObject.toBean(o2, ClassInfo.class);
JSONArray array = o2.getJSONArray("students");
System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
JSONObject object = (JSONObject) array.get(i);
Student studentaa = (Student) JSONObject.toBean(object,
Student.class);
cijson.getStudents().add(studentaa);
}
System.out.println(cijson);
}
public static JsonConfig getConfig() {
// 设置日期格式
JsonConfig config = new JsonConfig();
// 防止对象间的循环引用所产生的jsonString
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
config.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
public Object processObjectValue(String arg0, Object arg1,
JsonConfig arg2) {
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
Date d = (Date) arg1;
return sdf.format(d);
}
public Object processArrayValue(Object arg0, JsonConfig arg1) {
// TODO Auto-generated method stub
return null;
}
});
return config;
}
}
结果如下:
----------简单对象之间的转化-------------
(默认日期)简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":{"time":1466596005549,"minutes":46,"seconds":45,"hours":19,"month":5,"year":116,"timezoneOffset":-480,"day":3,"date":22}}
(设置日期)简单Bean转化为Json==={"id":1,"name":"李坤","birthDay":"2016-06-22 19:46:45.549"}
Json转为简单Bean===Student [birthDay=Wed Jun 22 19:46:45 CST 2016, id=1, name=李坤]
----------带泛型的List之间的转化-------------
带泛型的list转化为json==[{"id":1,"name":"李坤","birthDay":"2016-06-22 19:46:45.549"},{"id":2,"name":"曹贵生","birthDay":"2016-06-22 19:46:45.938"},{"id":3,"name":"柳波","birthDay":"2016-06-22 19:46:45.938"}]
李坤
曹贵生
柳波
李坤
曹贵生
柳波
ci to json //////////////
{"students":[{"id":1,"name":"李坤","birthDay":"2016-06-22 19:46:45.549"},{"id":2,"name":"曹贵生","birthDay":"2016-06-22 19:46:45.938"},{"id":3,"name":"柳波","birthDay":"2016-06-22 19:46:45.938"}],"className":"cna","teacher":{"name":"lijun","jabNum":"t101"},"classNum":101}
json to ci //////////
3
ClassInfo [className=cna, classNum=101, teacher=Teacher [name=lijun, jabNum=t101], students=[net.sf.ezmorph.bean.MorphDynaBean@331ae2ce[
{id=1, name=李坤, birthDay=2016-06-22 19:46:45.549}
], net.sf.ezmorph.bean.MorphDynaBean@36293b29[
{id=2, name=曹贵生, birthDay=2016-06-22 19:46:45.938}
], net.sf.ezmorph.bean.MorphDynaBean@4ceb1c86[
{id=3, name=柳波, birthDay=2016-06-22 19:46:45.938}
], Student [birthDay=Wed Jun 22 19:46:46 CST 2016, id=1, name=李坤], Student [birthDay=Wed Jun 22 19:46:46 CST 2016, id=2, name=曹贵生], Student [birthDay=Wed Jun 22 19:46:46 CST 2016, id=3, name=柳波]]]
以上的例子,相信能够解决我们大部分的问题,在此顺便提供其API,方便大家查看学习
http://json-lib.sourceforge.net/apidocs/jdk15/index.html