java与json之间的互操作.docx

上传人:b****5 文档编号:29965105 上传时间:2023-08-03 格式:DOCX 页数:33 大小:23.99KB
下载 相关 举报
java与json之间的互操作.docx_第1页
第1页 / 共33页
java与json之间的互操作.docx_第2页
第2页 / 共33页
java与json之间的互操作.docx_第3页
第3页 / 共33页
java与json之间的互操作.docx_第4页
第4页 / 共33页
java与json之间的互操作.docx_第5页
第5页 / 共33页
点击查看更多>>
下载资源
资源描述

java与json之间的互操作.docx

《java与json之间的互操作.docx》由会员分享,可在线阅读,更多相关《java与json之间的互操作.docx(33页珍藏版)》请在冰豆网上搜索。

java与json之间的互操作.docx

java与json之间的互操作

JSON-lib框架,转换JSON、XML不再困难

Json-lib可以将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象。

一、准备工作

1、首先要去官方下载json-lib工具包

下载地址:

目前最新的是2.4的版本,本示例中使用的是v2.3;json-lib还需要以下依赖包:

jakartacommons-lang2.5

jakartacommons-beanutils1.8.0

jakartacommons-collections3.2.1

jakartacommons-logging1.1.1

ezmorph1.0.6

官方网址:

http:

//json-

然后在工程中添加如下jar包:

当然你也可以用2.4的json-lib库

你可以在这里看看官方提供的示例:

http:

//json-

由于本次介绍的示例需要junit工具,所以你还需要添加junit的jar文件,版本是4.8.2版本的,下载地址:

如果你还不了解JSON是什么?

那么你应该可以看看http:

//www.json.org/json-zh.html

2、要转换的JavaBean的代码如下:

packagecom.hoo.entity;

 

publicclassStudent{

   privateintid;

   privateStringname;

   privateStringemail;

   privateStringaddress;

   privateBirthdaybirthday;

 

   //setter、getter

   publicStringtoString(){

       returnthis.name+"#"+this.id+"#"+this.address+"#"+this.birthday+"#"+this.email;

   }

}

 

Birthday.java

packagecom.hoo.entity;

 

publicclassBirthday{

   privateStringbirthday;

   

   publicBirthday(Stringbirthday){

       super();

       this.birthday=birthday;

   }

   //setter、getter

   publicBirthday(){}

   

   @Override

   publicStringtoString(){

       returnthis.birthday;

   }

}

注意,上面的getter、setter方法省略了,自己构建下。

3、新建JsonlibTest测试类,基本代码如下:

packagecom.hoo.test;

 

importjava.lang.reflect.InvocationTargetException;

importjava.util.ArrayList;

importjava.util.Collection;

importjava.util.Date;

importjava.util.HashMap;

importjava.util.Iterator;

importjava.util.List;

importjava.util.Map;

importjava.util.Set;

importnet.sf.json.JSON;

importnet.sf.json.JSONArray;

importnet.sf.json.JSONFunction;

importnet.sf.json.JSONObject;

importnet.sf.json.JSONSerializer;

importnet.sf.json.JsonConfig;

importnet.sf.json.processors.JsonValueProcessor;

importnet.sf.json.util.PropertyFilter;

importnet.sf.json.xml.XMLSerializer;

importmons.beanutils.PropertyUtils;

importorg.junit.After;

importorg.junit.Before;

importorg.junit.Test;

importcom.hoo.entity.Birthday;

importcom.hoo.entity.Student;

 

/**

 *function:

用json-lib转换java对象到JSON字符串

 *读取json字符串到java对象,序列化jsonObject到xml

 *json-lib-version:

json-lib-2.3-jdk15.jar

 *依赖包:

 *commons-beanutils.jar

 *commons-collections-3.2.jar

 *ezmorph-1.0.3.jar

 *commons-lang.jar

 *commons-logging.jar

 *@authorhoojo

 *@createDateNov28,20102:

28:

39PM

 *@fileJsonlibTest.java

 *@packagecom.hoo.test

 *@projectWebHttpUtils

 *@blog

 *@emailhoojo_@

 *@version1.0

 */

@SuppressWarnings({"deprecation","unchecked"})

publicclassJsonlibTest{

   privateJSONArrayjsonArray=null;

   privateJSONObjectjsonObject=null;

   

   privateStudentbean=null;

   

   @Before

   publicvoidinit(){

       jsonArray=newJSONArray();

       jsonObject=newJSONObject();

       

       bean=newStudent();

       bean.setAddress("address");

       bean.setEmail("email");

       bean.setId

(1);

       bean.setName("haha");

       Birthdayday=newBirthday();

       day.setBirthday("2010-11-22");

       bean.setBirthday(day);

   }

   

   @After

   publicvoiddestory(){

       jsonArray=null;

       jsonObject=null;

       bean=null;

       System.gc();

   }

   

   publicfinalvoidfail(Stringstring){

       System.out.println(string);

   }

   

   publicfinalvoidfailRed(Stringstring){

       System.err.println(string);

   }

   

}

上面的init会在每个方法之前运行,destory会在每个方法完成后执行。

分别用到了junit的@Before、@After注解,如果你对junit的这些注解不是很了解,可以看看junit官方的测试用例的example和doc;

JSONObject是将Java对象转换成一个json的Object形式,JSONArray是将一个Java对象转换成json的Array格式。

那什么是json的Object形式、Array形式?

用通俗易懂的方法将,所谓的json的Object形式就是一个花括号里面存放的如JavaMap的键值对,如:

{name:

’hoojo’,age:

24};

那么json的Array形式呢?

就是中括号,括起来的数组。

如:

[‘json’,true,22];

如果你还想了解更多json方面的知识,请看:

http:

//www.json.org/json-zh.html

除了上面的JSONArray、JSONObject可以将Java对象转换成JSON或是相反,将JSON字符串转换成Java对象,还有一个对象也可以完成上面的功能,它就是JSONSerializer;下面我们就来看看它们是怎么玩转Java对象和JSON的。

二、Java对象序列化成JSON对象

1、将JavaObject转换吃JSON字符串

在JsonlibTest中添加如下代码:

/*=========================JavaObject>>>>JSONString===========================*/

/**

 *function:

转JavaBean对象到JSON

 *@authorhoojo

 *@createDateNov28,20102:

35:

54PM

 */

@Test

publicvoidwriteEntity2JSON(){

   fail("==============JavaBean>>>JSONObject==================");

   fail(JSONObject.fromObject(bean).toString());

   fail("==============JavaBean>>>JSONArray==================");

   fail(JSONArray.fromObject(bean).toString());//array会在最外层套上[]

   fail("==============JavaBean>>>JSONObject==================");

   fail(JSONSerializer.toJSON(bean).toString());

   

   fail("========================JsonConfig========================");

   JsonConfigjsonConfig=newJsonConfig();  

   jsonConfig.registerJsonValueProcessor(Birthday.class,newJsonValueProcessor(){

       publicObjectprocessArrayValue(Objectvalue,JsonConfigjsonConfig){

           if(value==null){

               returnnewDate();

           }

           returnvalue;

       }

 

       publicObjectprocessObjectValue(Stringkey,Objectvalue,JsonConfigjsonConfig){

           fail("key:

"+key);

           returnvalue+"##修改过的日期";

       }

 

   });

   jsonObject=JSONObject.fromObject(bean,jsonConfig);

   

   fail(jsonObject.toString());

   Studentstudent=(Student)JSONObject.toBean(jsonObject,Student.class);

   fail(jsonObject.getString("birthday"));

   fail(student.toString());

   

   fail("#####################JsonPropertyFilter############################");

   jsonConfig.setJsonPropertyFilter(newPropertyFilter(){

       publicbooleanapply(Objectsource,Stringname,Objectvalue){

           fail(source+"%%%"+name+"--"+value);

           //忽略birthday属性

           if(value!

=null&&Birthday.class.isAssignableFrom(value.getClass())){

               returntrue;

           }

           returnfalse;

       }

   }); 

   fail(JSONObject.fromObject(bean,jsonConfig).toString());

   fail("#################JavaPropertyFilter##################");

   jsonConfig.setRootClass(Student.class);  

   jsonConfig.setJavaPropertyFilter(newPropertyFilter(){

       publicbooleanapply(Objectsource,Stringname,Objectvalue){

           fail(name+"@"+value+"#"+source);

           if("id".equals(name)||"email".equals(name)){

               value=name+"@@";

               returntrue;

           }

           returnfalse;

       }

   });  

   //jsonObject=JSONObject.fromObject(bean,jsonConfig);

   //student=(Student)JSONObject.toBean(jsonObject,Student.class);

   //fail(student.toString());

   student=(Student)JSONObject.toBean(jsonObject,jsonConfig);

   fail("Student:

"+student.toString());

}

fromObject将Java对象转换成json字符串,toBean将json对象转换成Java对象;

上面方法值得注意的是使用了JsonConfig这个对象,这个对象可以在序列化的时候对JavaObject的数据进行处理、过滤等

上面的jsonConfig的registerJsonValueProcessor方法可以完成对象值的处理和修改,比如处理生日为null时,给一个特定的值。

同样setJsonPropertyFilter和setJavaPropertyFilter都是完成对转换后的值的处理。

运行上面的代码可以在控制台看到如下结果:

==============JavaBean>>>JSONObject==================

{"address":

"address","birthday":

{"birthday":

"2010-11-22"},"email":

"email","id":

1,"name":

"haha"}

==============JavaBean>>>JSONArray==================

[{"address":

"address","birthday":

{"birthday":

"2010-11-22"},"email":

"email","id":

1,"name":

"haha"}]

==============JavaBean>>>JSONObject==================

{"address":

"address","birthday":

{"birthday":

"2010-11-22"},"email":

"email","id":

1,"name":

"haha"}

========================JsonConfig========================

key:

birthday

{"address":

"address","birthday":

"2010-11-22##修改过的日期","email":

"email","id":

1,"name":

"haha"}

2010-11-22##修改过的日期

haha#1#address#null#email

#####################JsonPropertyFilter############################

haha#1#address#2010-11-22#email%%%address--address

haha#1#address#2010-11-22#email%%%birthday--2010-11-22

haha#1#address#2010-11-22#email%%%email--email

haha#1#address#2010-11-22#email%%%id--1

haha#1#address#2010-11-22#email%%%name--haha

{"address":

"address","email":

"email","id":

1,"name":

"haha"}

#################JavaPropertyFilter##################

address@address#null#0#null#null#null

birthday@2010-11-22##修改过的日期#null#0#address#null#null

email@email#null#0#address#null#null

id@1#null#0#address#null#null

name@haha#null#0#address#null#null

Student:

haha#0#address#null#null

2、将JavaList集合转换吃JSON字符串

/**

 *function:

转换JavaList集合到JSON

 *@authorhoojo

 *@createDateNov28,20102:

36:

15PM

 */

@Test

publicvoidwriteList2JSON(){

   fail("==============JavaList>>>JSONArray==================");

   Liststu=newArrayList();

   stu.add(bean);

   bean.setName("jack");

   stu.add(bean);

   fail(JSONArray.fromObject(stu).toString());

   fail(JSONSerializer.toJSON(stu).toString());

}

运行此方法后,可以看到控制台输出:

==============JavaList>>>JSONArray==================

[{"address":

"address","birthday":

{"birthday":

"2010-11-22"},"email":

"email","id":

1,"name":

"jack"},

{"address":

"address","birthday":

{"birthday":

"2010-11-22"},"email":

"email","id":

1,"name":

"jack"}]

[{"address":

"address","birthday":

{"birthday":

"2010-11-22"},"email":

"email","id":

1,"name":

"jack"},

{"address":

"address","birthday":

{"birthday":

"2010-11-22"},"email":

"email","id":

1,"name":

"jack"}]

如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。

如果你用JSONObject.fromObject方法转换List会出现异常,通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。

3、将Map集合转换成JSON对象

/**

 *function:

转JavaMap对象到JSON

 *@authorhoojo

 *@createDateNov28,20102:

37:

35PM

 */

@Test

publicvoidwriteMap2JSON(){

   Mapmap=newHashMap();

 

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > PPT模板 > 商务科技

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1