gjson应用

1.简单的处理list和map

Java代码

1.Gsongson=newGson();

2.ListtestList=newArrayList();

3.testList.add("first");

4.testList.add("second");

5.StringlistToJson=gson.toJson(testList);

6.System.out.println(listToJson);

7.//prints["first","second"]

8.

9.MaptestMap=newHashMap();

10.testMap.put("id","id.first");

11.testMap.put("name","name.second");

12.StringmapToJson=gson.toJson(testMap);

13.System.out.println(mapToJson);

14.//prints{"id":"id.first","name":"name.second"}

Gsongson=newGson();

ListtestList=newArrayList();

testList.add("first");

testList.add("second");

StringlistToJson=gson.toJson(testList);

System.out.println(listToJson);

//prints["first","second"]

MaptestMap=newHashMap();

testMap.put("id","id.first");

testMap.put("name","name.second");

StringmapToJson=gson.toJson(testMap);

System.out.println(mapToJson);

//prints{"id":"id.first","name":"name.second"}

2.处理带泛型的集合

Java代码

1.List<TestBean>testBeanList=newArrayList<TestBean>();

2.TestBeantestBean=newTestBean();

3.testBean.setId("id");

4.testBean.setName("name");

5.testBeanList.add(testBean);

List<TestBean>testBeanList=newArrayList<TestBean>();

TestBeantestBean=newTestBean();

testBean.setId("id");

testBean.setName("name");

testBeanList.add(testBean);

Java代码

1.java.lang.reflect.Typetype=newcom.google.gson.reflect.TypeToken<List<T

estBean>>(){

2.}.getType();

3.StringbeanListToJson=gson.toJson(testBeanList,type);

4.System.out.println(beanListToJson);

5.//prints[{"id":"id","name":"name"}]

6.

7.List<TestBean>testBeanListFromJson=gson.fromJson(beanListToJson,type);

8.System.out.println(testBeanListFromJson);

9.//prints[TestBean@1ea5671[id=id,name=name,birthday=<null>]]

java.lang.reflect.Typetype=new

com.google.gson.reflect.TypeToken<List<TestBean>>(){

}.getType();

StringbeanListToJson=gson.toJson(testBeanList,type);

System.out.println(beanListToJson);

//prints[{"id":"id","name":"name"}]

List<TestBean>testBeanListFromJson=gson.fromJson(beanListToJson,type);

System.out.println(testBeanListFromJson);

//prints[TestBean@1ea5671[id=id,name=name,birthday=<null>]]

map等其他集合类型同上

3.Date类型转化

先写工具类

Java代码

1.importjava.lang.reflect.Type;

2.

3.importcom.google.gson.JsonDeserializationContext;

4.importcom.google.gson.JsonDeserializer;

5.importcom.google.gson.JsonElement;

6.importcom.google.gson.JsonParseException;

7.

8.publicclassUtilDateDeserializerimplementsJsonDeserializer<java.util.Da

te>{

9.

10.@Override

11.publicjava.util.Datedeserialize(JsonElementjson,TypetypeOfT,Jso

nDeserializationContextcontext)

12.throwsJsonParseException{

13.returnnewjava.util.Date(json.getAsJsonPrimitive().getAsLong());

14.}

15.}

importjava.lang.reflect.Type;

importcom.google.gson.JsonDeserializationContext;

importcom.google.gson.JsonDeserializer;

importcom.google.gson.JsonElement;

importcom.google.gson.JsonParseException;

publicclassUtilDateDeserializerimplementsJsonDeserializer<java.util.Date>{

@Override

publicjava.util.Datedeserialize(JsonElementjson,TypetypeOfT,

JsonDeserializationContextcontext)

throwsJsonParseException{

returnnewjava.util.Date(json.getAsJsonPrimitive().getAsLong());

}

}

Java代码

1.importjava.lang.reflect.Type;

2.

3.importcom.google.gson.JsonElement;

4.importcom.google.gson.JsonPrimitive;

5.importcom.google.gson.JsonSerializationContext;

6.importcom.google.gson.JsonSerializer;

7.

8.publicclassUtilDateSerializerimplementsJsonSerializer<java.util.Date>

{

9.

10.@Override

11.publicJsonElementserialize(java.util.Datesrc,TypetypeOfSrc,

12.JsonSerializationContextcontext){

13.returnnewJsonPrimitive(src.getTime());

14.}

15.

16.}

importjava.lang.reflect.Type;

importcom.google.gson.JsonElement;

importcom.google.gson.JsonPrimitive;

importcom.google.gson.JsonSerializationContext;

importcom.google.gson.JsonSerializer;

publicclassUtilDateSerializerimplementsJsonSerializer<java.util.Date>{

@Override

publicJsonElementserialize(java.util.Datesrc,TypetypeOfSrc,

JsonSerializationContextcontext){

returnnewJsonPrimitive(src.getTime());

}

}

Java代码

1./**

2.*序列化方法

3.*@parambean

4.*@paramtype

5.*@return

6.*/

7.publicstaticStringbean2json(Objectbean,Typetype){

8.Gsongson=newGsonBuilder().registerTypeAdapter(java.util.Date.c

lass,newUtilDateSerializer())

9..setDateFormat(DateFormat.LONG).create();

10.returngson.toJson(bean);

11.}

12.

13./**

14.*反序列化方法

15.*@paramjson

16.*@paramtype

17.*@return

18.*/

19.publicstatic<T>Tjson2bean(Stringjson,Typetype){

20.Gsongson=newGsonBuilder().registerTypeAdapter(java.util.Date.

class,newUtilDateDeserializer())

21..setDateFormat(DateFormat.LONG).create();

22.returngson.fromJson(json,type);

23.}

/**

*序列化方法

*@parambean

*@paramtype

*@return

*/

publicstaticStringbean2json(Objectbean,Typetype){

Gsongson=newGsonBuilder().registerTypeAdapter(java.util.Date.class,new

UtilDateSerializer())

.setDateFormat(DateFormat.LONG).create();

returngson.toJson(bean);

}

/**

*反序列化方法

*@paramjson

*@paramtype

*@return

*/

publicstatic<T>Tjson2bean(Stringjson,Typetype){

Gsongson=newGsonBuilder().registerTypeAdapter(java.util.Date.class,new

UtilDateDeserializer())

.setDateFormat(DateFormat.LONG).create();

returngson.fromJson(json,type);

}

现在开始测试

Java代码

1.List<TestBean>testBeanList=newArrayList<TestBean>();

2.TestBeantestBean=newTestBean();

3.testBean.setId("id");

4.testBean.setName("name");

5.testBean.setBirthday(newjava.util.Date());

6.testBeanList.add(testBean);

7.

8.java.lang.reflect.Typetype=newcom.google.gson.reflect.TypeToken<List<T

estBean>>(){

9.}.getType();

10.StringbeanListToJson=bean2json(testBeanList,type);

11.System.out.println("beanListToJson:"+beanListToJson);

12.//prints[{"id":"id","name":"name","birthday":1256531559390}]

13.

14.List<TestBean>testBeanListFromJson=json2bean(beanListToJson,type);

15.System.out.println(testBeanListFromJson);

16.//prints[TestBean@77a7f9[id=id,name=name,birthday=MonOct2612:39:05CS

T2009]]

List<TestBean>testBeanList=newArrayList<TestBean>();

TestBeantestBean=newTestBean();

testBean.setId("id");

testBean.setName("name");

testBean.setBirthday(newjava.util.Date());

testBeanList.add(testBean);

java.lang.reflect.Typetype=new

com.google.gson.reflect.TypeToken<List<TestBean>>(){

}.getType();

StringbeanListToJson=bean2json(testBeanList,type);

System.out.println("beanListToJson:"+beanListToJson);

//prints[{"id":"id","name":"name","birthday":1256531559390}]

List<TestBean>testBeanListFromJson=json2bean(beanListToJson,type);

System.out.println(testBeanListFromJson);

//prints[TestBean@77a7f9[id=id,name=name,birthday=MonOct2612:39:05CST2009]]

后记:对于java.sql.Date的转化同上类似,写两个类用于其序列化和反序列化即可

SQLDateDeserializerimplementsJsonDeserializer<java.sql.Date>

SQLDateSerializerimplementsJsonSerializer<java.sql.Date>

GsonBuilderapi:

com.google.gson

ClassGsonBuilder

java.lang.Object

com.google.gson.GsonBuilder

publicfinalclassGsonBuilderextendsObject

UsethisbuildertoconstructaGsoninstancewhenyouneedtosetconfiguration

optionsotherthanthedefault.ForGsonwithdefaultconfiguration,itis

simplertousenewGson().GsonBuilderisbestusedbycreatingit,andthen

invokingitsvariousconfigurationmethods,andfinallycallingcreate.

ThefollowingisanexampleshowshowtousetheGsonBuildertoconstructaGson

instance:

Gsongson=newGsonBuilder()

.registerTypeAdapter(Id.class,newIdTypeAdapter())

.serializeNulls()

.setDateFormat(DateFormat.LONG)

.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)

.setPrettyPrinting()

.setVersion(1.0)

.create();

NOTE:theorderofinvocationofconfigurationmethodsdoesnotmatter.

Author:

InderjeetSingh,JoelLeitch

ConstructorSummary

GsonBuilder()

CreatesaGsonBuilderinstancethatcanbeusedtobuildGsonwith

variousconfigurationsettings.

MethodSummary

Gsoncreate()

CreatesaGsoninstancebasedonthecurrent

configuration.

GsonBuilderexcludeFieldsWithModifiers(int...modifiers)

ConfiguresGsontoexcludesallclassfieldsthathave

thespecifiedmodifiers.

GsonBuilderexcludeFieldsWithoutExposeAnnotation()

ConfiguresGsontoexcludeallfieldsfromconsideration

forserializationordeserializationthatdonothavetheExpose

annotation.

GsonBuilderregisterTypeAdapter(Typetype,ObjecttypeAdapter)

ConfiguresGsonforcustomserializationor

deserialization.

GsonBuilderserializeNulls()

ConfigureGsontoserializenullfields.

GsonBuildersetDateFormat(intstyle)

ConfiguresGsontotoserializeDateobjectsaccording

tothestylevalueprovided.

GsonBuildersetDateFormat(intdateStyle,inttimeStyle)

ConfiguresGsontotoserializeDateobjectsaccording

tothestylevalueprovided.

GsonBuildersetDateFormat(Stringpattern)

ConfiguresGsontoserializeDateobjectsaccordingto

thepatternprovided.

GsonBuildersetFieldNamingPolicy(FieldNamingPolicynamingConvention)

ConfiguresGsontoapplyaspecificnamingpolicytoan

object'sfieldduringserializationanddeserialization.

GsonBuildersetPrettyPrinting()

ConfiguresGsontooutputJsonthatfitsinapagefor

批注[1]:========CONSTRUCTOR

SUMMARY========

批注[2]:

批注[3]:==========METHOD

SUMMARY===========

批注[4]:

prettyprinting.

GsonBuildersetVersion(doubleignoreVersionsAfter)

ConfiguresGsontoenableversioningsupport.

Methodsinheritedfromclassjava.lang.Object

equals,getClass,hashCode,notify,notifyAll,toString,wait,wait,wait

ConstructorDetail

GsonBuilder

publicGsonBuilder()

CreatesaGsonBuilderinstancethatcanbeusedtobuildGsonwithvarious

configurationsettings.GsonBuilderfollowsthebuilderpattern,anditis

typicallyusedbyfirstinvokingvariousconfigurationmethodstoset

desiredoptions,andfinallycallingcreate().

MethodDetail

setVersion

publicGsonBuildersetVersion(doubleignoreVersionsAfter)

ConfiguresGsontoenableversioningsupport.

Parameters:

ignoreVersionsAfter-anyfieldortypemarkedwithaversionhigher

thanthisvalueareignoredduringserializationordeserialization.

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

excludeFieldsWithModifiers

publicGsonBuilderexcludeFieldsWithModifiers(int...modifiers)

ConfiguresGsontoexcludesallclassfieldsthathavethespecified

modifiers.Bydefault,Gsonwillexcludeallfieldsmarkedtransientor

static.Thismethodwilloverridethatbehavior.

批注[5]:

批注[6]:=========CONSTRUCTOR

DETAIL========

批注[7]:

批注[8]:

批注[9]:============METHOD

DETAIL==========

批注[10]:

批注[11]:

批注[12]:

Parameters:

modifiers-thefieldmodifiers.Youmustusethemodifiersspecified

intheModifierclass.Forexample,Modifier.TRANSIENT,

Modifier.STATIC.

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

excludeFieldsWithoutExposeAnnotation

publicGsonBuilderexcludeFieldsWithoutExposeAnnotation()

ConfiguresGsontoexcludeallfieldsfromconsiderationforserialization

ordeserializationthatdonothavetheExposeannotation.

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

serializeNulls

publicGsonBuilderserializeNulls()

ConfigureGsontoserializenullfields.Bydefault,Gsonomitsallfields

thatarenullduringserialization.

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

Since:

1.2

setFieldNamingPolicy

publicGsonBuildersetFieldNamingPolicy(FieldNamingPolicynamingConvention)

ConfiguresGsontoapplyaspecificnamingpolicytoanobject'sfield

duringserializationanddeserialization.

Parameters:

namingConvention-theJSONfieldnamingconventiontousefor

serializationanddeserialization.

批注[13]:

批注[14]:

批注[15]:

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

setPrettyPrinting

publicGsonBuildersetPrettyPrinting()

ConfiguresGsontooutputJsonthatfitsinapageforprettyprinting.

ThisoptiononlyaffectsJsonserialization.

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

setDateFormat

publicGsonBuildersetDateFormat(Stringpattern)

ConfiguresGsontoserializeDateobjectsaccordingtothepatternprovided.

YoucancallthismethodorsetDateFormat(int)multipletimes,butonlythe

lastinvocationwillbeusedtodecidetheserializationformat.

Notethatthispatternmustabidebytheconventionprovidedby

SimpleDateFormatclass.SeethedocumentationinSimpleDateFormatformore

informationonvaliddateandtimepatterns.

Parameters:

pattern-thepatternthatdateswillbeserialized/deserialized

to/from

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

Since:

1.2

setDateFormat

publicGsonBuildersetDateFormat(intstyle)

ConfiguresGsontotoserializeDateobjectsaccordingtothestylevalue

provided.YoucancallthismethodorsetDateFormat(String)multipletimes,

批注[16]:

批注[17]:

批注[18]:

butonlythelastinvocationwillbeusedtodecidetheserialization

format.

Notethatthisstylevalueshouldbeoneofthepredefinedconstantsinthe

DateFormatclass.SeethedocumentationinDateFormatformoreinformation

onthevalidstyleconstants.

Parameters:

style-thepredefineddatestylethatdateobjectswillbe

serialized/deserializedto/from

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

Since:

1.2

setDateFormat

publicGsonBuildersetDateFormat(intdateStyle,

inttimeStyle)

ConfiguresGsontotoserializeDateobjectsaccordingtothestylevalue

provided.YoucancallthismethodorsetDateFormat(String)multipletimes,

butonlythelastinvocationwillbeusedtodecidetheserialization

format.

Notethatthisstylevalueshouldbeoneofthepredefinedconstantsinthe

DateFormatclass.SeethedocumentationinDateFormatformoreinformation

onthevalidstyleconstants.

Parameters:

dateStyle-thepredefineddatestylethatdateobjectswillbe

serialized/deserializedto/from

timeStyle-thepredefinedstyleforthetimeportionofthedate

objects

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

Since:

1.2

registerTypeAdapter

publicGsonBuilderregisterTypeAdapter(Typetype,

批注[19]:

批注[20]:

ObjecttypeAdapter)

ConfiguresGsonforcustomserializationordeserialization.Thismethod

combinestheregistrationofanInstanceCreator,JsonSerializer,anda

JsonDeserializer.ItisbestusedwhenasingleobjecttypeAdapter

implementsalltherequiredinterfacesforcustomserializationwithGson.

Ifaninstancecreator,serializerordeserializerwaspreviously

registeredforthespecifiedtype,itisoverwritten.

Parameters:

type-thetypedefinitionforthetypeadapterbeingregistered

typeAdapter-Thisobjectmustimplementatleastoneofthe

InstanceCreator,JsonSerializer,andaJsonDeserializerinterfaces.

Returns:

areferencetothisGsonBuilderobjecttofulfillthe"Builder"

pattern

create

publicGsoncreate()

CreatesaGsoninstancebasedonthecurrentconfiguration.Thismethodis

freeofside-effectstothisGsonBuilderinstanceandhencecanbecalled

multipletimes.

Returns:

aninstanceofGsonconfiguredwiththeoptionscurrentlysetinthis

builder

批注[21]:

相关推荐