jsonobject java_JSON详细学习之JSONObject in JAVA

这篇博客介绍了在Java中使用JSONObject和JSONArray进行JSON操作的方法,包括创建JSONObject、从HashMap转换、创建JSONArray以及从ArrayList转换。还展示了如何解析JSON字符串,并提供了涉及日期格式化的示例。此外,博主展示了如何将Java对象转换为JSON和从JSON转换回Java对象,包括处理带有泛型的List。最后,给出了处理复杂JSON对象和避免循环引用的配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要依赖的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字符串的解析:

packagecom.peter.jsonobj.test;

importjava.util.ArrayList;

importjava.util.HashMap;

importnet.sf.json.JSONArray;

importnet.sf.json.JSONObject;

publicclassTest2 {

publicstaticvoidmain(String[] args) {

//JsonObject和JsonArray区别就是JsonObject是对象形式,JsonArray是数组形式

//创建JsonObject第一种方法

JSONObject jsonObject = newJSONObject();

jsonObject.put("UserName","ZHULI");

jsonObject.put("age","30");

jsonObject.put("workIn","ALI");

System.out.println("jsonObject1:"+ jsonObject);

//创建JsonObject第二种方法

HashMap hashMap = newHashMap();

hashMap.put("UserName","ZHULI");

hashMap.put("age","30");

hashMap.put("workIn","ALI");

System.out.println("jsonObject2:"+ JSONObject.fromObject(hashMap));

//创建一个JsonArray方法1

JSONArray jsonArray = newJSONArray();

jsonArray.add(0,"ZHULI");

jsonArray.add(1,"30");

jsonArray.add(2,"ALI");

System.out.println("jsonArray1:"+ jsonArray);

//创建JsonArray方法2

ArrayList arrayList = newArrayList();

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 = newJSONObject();

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(inti =0; 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:ZHULIArray:ZHULI Array:30 Array:ALI

由于我们涉及更多的是对象(Bean)与Json字符串之间的转换.这里我创建了我的Model类

packagecom.peter.model;

importjava.io.Serializable;

importjava.util.ArrayList;

importjava.util.List;

publicclassClassInfoimplementsSerializable{

privateString className;

privateintclassNum;

privateTeacher teacher;

privateList students=newArrayList();

publicString getClassName() {

returnclassName;

}

publicvoidsetClassName(String className) {

this.className = className;

}

publicTeacher getTeacher() {

returnteacher;

}

publicvoidsetTeacher(Teacher teacher) {

this.teacher = teacher;

}

publicList getStudents() {

returnstudents;

}

publicvoidsetStudents(List students) {

this.students = students;

}

publicintgetClassNum() {

returnclassNum;

}

publicvoidsetClassNum(intclassNum) {

this.classNum = classNum;

}

@Override

publicString toString() {

return"ClassInfo [className="+ className +", classNum="+ classNum

+ ", teacher="+ teacher +", students="+ students +"]";

}

}

packagecom.peter.model;

importjava.io.Serializable;

importjava.util.Date;

publicclassStudentimplementsSerializable{

privateintid;

privateString name;

privateDate birthDay;

publicintgetId() {

returnid;

}

publicvoidsetId(intid) {

this.id = id;

}

publicString getName() {

returnname;

}

publicvoidsetName(String name) {

this.name = name;

}

publicDate getBirthDay() {

returnbirthDay;

}

publicvoidsetBirthDay(Date birthDay) {

this.birthDay = birthDay;

}

@Override

publicString toString() {

return"Student [birthDay="+ birthDay +", id="+ id +", name="

+ name + "]";

}

}

packagecom.peter.model;

importjava.io.Serializable;

publicclassTeacherimplementsSerializable{

privateString name;

privateString jabNum;

publicString getName() {

returnname;

}

publicvoidsetName(String name) {

this.name = name;

}

publicString getJabNum() {

returnjabNum;

}

publicvoidsetJabNum(String jabNum) {

this.jabNum = jabNum;

}

@Override

publicString toString() {

return"Teacher [name="+ name +", jabNum="+ jabNum +"]";

}

}

以上的model基本上能满足所有的Json字符串格式.

packagecom.peter.jsonobj.test;

importjava.text.SimpleDateFormat;

importjava.util.ArrayList;

importjava.util.Date;

importjava.util.List;

importnet.sf.json.JSONArray;

importnet.sf.json.JSONObject;

importnet.sf.json.JSONSerializer;

importnet.sf.json.JsonConfig;

importnet.sf.json.processors.JsonValueProcessor;

importnet.sf.json.util.CycleDetectionStrategy;

importcom.peter.model.ClassInfo;

importcom.peter.model.Student;

importcom.peter.model.Teacher;

publicclassTest {

publicstaticvoidmain(String[] args) {

Student student1 = newStudent();

student1.setId(1);

student1.setName("李坤");

student1.setBirthDay(newDate());

// //

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 = newStudent();

student2.setId(2);

student2.setName("曹贵生");

student2.setBirthDay(newDate());

Student student3 = newStudent();

student3.setId(3);

student3.setName("柳波");

student3.setBirthDay(newDate());

List list = newArrayList();

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 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 = newTeacher();

t.setJabNum("t101");

t.setName("lijun");

ClassInfo ci = newClassInfo();

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(inti =0; i 

JSONObject object = (JSONObject) array.get(i);

Student studentaa = (Student) JSONObject.toBean(object,

Student.class);

cijson.getStudents().add(studentaa);

}

System.out.println(cijson);

}

publicstaticJsonConfig getConfig() {

// 设置日期格式

JsonConfig config = newJsonConfig();

// 防止对象间的循环引用所产生的jsonString

config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

config.registerJsonValueProcessor(Date.class,newJsonValueProcessor() {

publicObject processObjectValue(String arg0, Object arg1,

JsonConfig arg2) {

SimpleDateFormat sdf = newSimpleDateFormat(

"yyyy-MM-dd HH:mm:ss.SSS");

Date d = (Date) arg1;

returnsdf.format(d);

}

publicObject processArrayValue(Object arg0, JsonConfig arg1) {

// TODO Auto-generated method stub

returnnull;

}

});

returnconfig;

}

}结果如下:

----------简单对象之间的转化-------------(默认日期)简单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,方便大家查看学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值