JSON是什么?
JSON的全称是JavaScriptObjectNotation,是一种轻量级的数据交换格式。JSO
N与XML具有相同的特性,例如易于人编写和阅读,易于机器生成和解析。但是JSON比
XML数据传输的有效性要高出很多。JSON完全独立与编程语言,使用文本格式保存。
JSON数据有两种结构:
•Name-Value对构成的集合,类似于Java中的Map。
•Value的有序列表,类似于Java中的Array。
一个JSON格式的数据示例:
{
"Name":"Apple",
"Expiry":"2007/10/1113:54",
"Price":3.99,
"Sizes":[
"Small",
"Medium",
"Large"
]
}
更多关于JSON数据格式的说明参看JSON官方网站:(中文
内容参看:/)
GWT与JSON
GWT中支持的客户端服务器端方法调用和数据传递的标准格式是RPC。JSON并不
是GWT支持的标准的数据传递格式。那么如何使用JSON来作为GWT的数据传递格式
呢?需要以下几步。
第一,引用HTTP和JSON支持。
第二,在客户端创建JSON数据,提交到服务器
第三,在服务器上重写数据格式解析的代码,使之支持JSON格式的数据
第四,在服务器上组织JSON格式的数据,返回给客户端。
第五,客户端解析服务器传回的JSON数据,正确的显示
引用HTTP和JSON支持
找到.文件,在其中的
在之后添加如下的内容:
其中指的是要使用JSON,.H
TTP值得是通过HTTP调用服务器上的服务方法。
客户端构造JSON数据
客户端需要使用包内的类来组装JSON格式的数据,
数据格式如下:
组合一个简单的JSON数据:
数据类型说明
JSONArrayJSONValue构成的数组类型
JSONBooleanJSONboolean值
JSONException
访问JSON结构的数据出错的情况下可以抛出此异
常
JSONNullJSONNull根式的数据
JSONNumberJSONNumber类型的数据
JSONObjectJSONObject类型的数据
JSONParr
将String格式的JSON数据解析为JSONValue类
型的数据
JSONStringJSONString类型的数据
JSONValue所有JSON类型值的超级类型
JSONObjectinput=newJSONObject();
JSONStringvalue=newJSONString("mazhao");
("name",value);
JSON数据格式为:{name:"mazhao"}
组合一个包含数组类型的复杂JSON数据:
JSONObjectinput=newJSONObject();
JSONStringvalue=newJSONString("mazhao");
("name",value);
JSONArrayarrayValue=newJSONArray();
(0,newJSONString("arrayitem0"));
(1,newJSONString("arrayitem1"));
(2,newJSONString("arrayitem2"));
("array",arrayValue);
JSON数据格式为:
{name:"mazhao",
array:{"arrayitem0","arrayitem1","arrayitem2"}}
注意上述的JSON类型的数据,使用的都是包内的类
型。这些类型最终会被编译为JavaScript执行。
服务端重写数据解析代码,支持JSON格式的数据
在服务器上,需要使用JSONJava支持类才能将JSON格式的数据转换为各种类型
的数据,当然也可以自己写一些解析用的代码。这里我们使用了上的代码
来完成。这组代码与的代码很相似,只是在包内
部。
怎么解析JSON术诀呢?针对上述中的复杂的JSON数据:
{name:"mazhao",
array:{"arrayitem0","arrayitem1","arrayitem2"}}
可以使用如下的方式解析:
JSONObjectjsonObject=newJSONObject(payload);
Stringname=ing("name");
n("nameis:"+name);
JSONArrayjsonArray=NArray("array");
for(inti=0;i<();i++){
n("item"+i+":"+ing(i));
}
其中payload指的是上述的JSON格式的数据。
那么如何写GWT的Service来得到Payload的数据呢?需要两点,第一,需要建立
一个Service类,第二,覆盖父类的processCall方法。
示例代码:
;
izationException;
ServiceServlet;
orldService;
ray;
ception;
ject;
/**
*CreatedbyIntelliJIDEA.
*Ur:vaio
*Date:2007-9-4
*Time:22:08:31
*TochangethistemplateuFile|Settings|FileTemplates.
*/
publicclassHelloWorldServiceImplextendsRemoteServiceServletimplements
HelloWorldService{
publicStringprocessCall(Stringpayload)throwsSerializationException{
try{
JSONObjectjsonObject=newJSONObject(payload);
Stringname=ing("name");
n("nameis:"+name);
JSONArrayjsonArray=NArray("array");
for(inti=0;i<();i++){
n("item"+i+":"+ing(i));
}
}catch(JSONExceptione){
tackTrace();//TochangebodyofcatchstatementuFile|
Settings|FileTemplates.
}
return"success";
}
}
在服务器上组织
JSON
格式的数据,返回给客户端
同上
客户端解析服务器传回的JSON数据,正确的显示
同上
Struts2
返回
json
需要
jsonplugin-0[1].25
的
包
然后我们的配置文件中需要继承json-default
Java代码
1.<?xmlversion="1.0"encoding="UTF-8"?>
2.
3."-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//
EN"
4."/dtds/">
5.
6.
7.
8.
espace="/">
9.
"method="testUr">
10.
11.
12.
13.
14.
<?xmlversion="1.0"encoding="UTF-8"?>
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"/dtds/">
namespace="/">
method="testUr">
然后我们的Action中需要返回的json信息需要加上注解
Java代码
1.//pizza
on;
3.
ist;
;
6.
;
Support;
9.
classJsonActionextendsActionSupport{
11.
estaticfinallongrialVersionUID=-
4669835L;
13.
r=newUrs();
erList=newArrayList();
16.
17.
StringtestUr(){
n("inthejsonActon");
it();
(ur);
SUCCESS;
23.}
24.
voidurInit(){
(1);
e("张泽峰");
28.
sword("nofengPassword");
29.}
30.
31.@JSON(name="urString")
UrsgetUr(){
33.
returnur;
34.}
35.
36.@JSON(name="urList")
ListgetUrList(){
38.
returnurList;
39.}
40.
voidtUr(Ursur){
=ur;
43.
}
44.
voidtUrList(ListurList){
st=urList;
47.}
48.
49.
50.}
JSONPlugin
的说明
EditPageBrowSpaceAddPageAddNews
AddedbyMusachyBarroso,lasteditedbyghostrolleronJul04,2008(viewchange)SHOWCOMMENT
NameJSONPlugin
PublisherMusachyBarroso
Licen
OpenSource(ASL2)
Version0.30
CompatibilityStruts2.0.6orlater
Homepage/p/jsonplugin/
Download/p/jsonplugin/downloads/list
Overview
TheJSONpluginprovidesa"json"ialization
processisrecursive,meaningthatthewholeobjectgraph,startingontheactionclass(ba
classnotincluded)willberialized(rootobjectcanbecustomizedusingthe"root"attribute).
Iftheinterceptorisud,theactionwillbepopulatedfromtheJSONcontentintherequest,
thearetherulesoftheinterceptor:
1.
The"content-type"mustbe"application/json"
Ncontentmustbewellformed,grammar.
musthaveapublic"tter"methodforfieldsthatmustbepopulated.
tedtypesforpopulationare:Primitives(int,long...String),Date,List,Map,
PrimitiveArrays,Otherclass(moreonthislater),andArrayofOtherclass.
5.
AnyobjectinJSON,thatistobepopulatedinsidealist,oramap,willbeoftypeMap
(mappingfrompropertiestovalues),anywholenumberwillbeoftypeLong,any
decimalnumberwillbeoftypeDouble,andanyarrayoftypeList.
GiventhisJSONstring:
{
"doubleValue":10.10,
"nestedBean":{
"name":"MrBean"
},
"list":["A",10,20.20,{
"firstName":"ElZorro"
}],
"array":[10,20]
}
Theactionmusthavea"tDoubleValue"method,takingeithera"float"ora"double"argument
(theinterceptorwillconvertthevaluetotherightone).Theremustbea"tNestedBean"
whoargumenttypecanbeanyclass,thathasa"tName"methodtakingasargumentan
"String".Theremustbea"tList"methodthattakesa"List"asargument,thatlistwillcontain:
"A"(String),10(Long),20.20(Double),Map("firstName"->"ElZorro").The"tArray"
methodcantakeasparametereithera"List",oranynumericarray.
Rating?
•
1
•2
•3
•
4
•
5
Installation
Thisplugincanbeinstalledbycopyingthepluginjarintoyourapplication's/WEB-INF/lib
rfilesneedtobecopiedorcreated.
Toumaven,addthistoyourpom:
...
...
/svn/trunk/
CustomizingSerializationandDerialization
UtheJSONannotationtocustomizetherialization/bleJSON
annotationfields:
NameDescriptionDefaultValue
SerializationDerialization
nameCustomizefieldnameemptyyesno
rialize
Includein
rialization
trueyesno
derialize
Includein
derialization
truenoyes
Excludingproperties
Acomma-delimitedlistofregularexpressionscanbepasdtotheJSONResultandInterceptor,
propertiesmatchinganyoftheregularexpressionswillbeignoredontherializationprocess:
rd,
studentList.*.sin
rd,
studentList.*.sin
Includingproperties
Acomma-delimitedlistofregularexpressionscanbepasdtotheJSONResulttorestrict
opertiesmatchinganyoftheregularexpressions
willbeincludedintherializedoutput.
^entries[d+].clientNumber,
format
Formatudto
format/paraDate
field
"yyyy-MM-dd'T'HH:mm:ss"yesyes
Note
Excludepropertyexpressionstakeprecedenceoverincludeproperty
,ifyouuincludeandexcludepropertyexpressions
onthesameresult,includepropertyexpressionswillnotbeappliedifan
excludeexcludepropertyexpressionmatchesapropertyfirst.
^entries[d+].scheduleNumber,
^entries[d+].createUrId
RootObject
Uthe"root"attribute(OGNLexpression)tospecifytherootobjecttoberialized.
The"root"attribute(OGNLexpression)canalsobeudontheinterceptortospecifytheobject
thatmustbepopulated,makesurethisobjectisnotnull.
WrapwithComments
Ifthe"wrapWithComments"(falbydefault)attributeisttotrue,thegeneratedJSONis
wrappedwithcommentslike:
/*{
"doubleVal":10.10,
"nestedBean":{
"name":"MrBean"
},
"list":["A",10,20.20,{
"firstName":"ElZorro"
}],
"array":[10,20]
}*/
example,
["*/alert('XSS');/*"]
ThankstoDouglasCrockfordforthetip!
pthocommentsu:
varresponObject=eval("("+ing(f("*")+2,
dexOf("*"))+")");
BaClass
Bydefaultpropertiesdefinedonbaclassofthe"root"objectwon'tberialized,torialize
propertiesinallbaclass(uptoObject)t"ignoreHierarchy"tofalintheJSONresult:
Enumerations
Bydefault,anEnumisrializedasaname=valuepairwherevalue=name().
publicenumAnEnum{
ValueA,
ValueB
}
JSON:"myEnum":"ValueA"
Uthe"enumAsBean"resultparametertorializeEnum'sasabeanwithaspecialproperty
_namewithvaluename().Allpropertiesoftheenumarealsorialized.
publicenumAnEnum{
ValueA("A"),
ValueB("B");
privateStringval;
publicAnEnum(val){
=val;
}
publicgetVal(){
returnval;
}
}
JSON:myEnum:{"_name":"ValueA","val":"A"}
:
Compressingtheoutput.
uestmust
include"gzip"inthe"Accept-Encoding"headerforthistowork.
Example
SetupAction
Thissimpleactionhassomefields:
Example:
p;
;
;
publicclassJSONExample{
privateStringfield1="str";
privateint[]ints={10,20};
privateMapmap=newHashMap();
privateStringcustomName="custom";
//'transient'fieldsarenotrialized
privatetransientStringfield2;
//fieldswithoutgettermethodarenotrialized
privateStringfield3;
publicStringexecute(){
("John","Galt");
S;
}
publicStringgetField1(){
returnfield1;
}
publicvoidtField1(Stringfield1){
1=field1;
}
publicint[]getInts(){
returnints;
}
publicvoidtInts(int[]ints){
=ints;
}
publicMapgetMap(){
returnmap;
}
publicvoidtMap(Mapmap){
=map;
}
@JSON(name="newName")
publicStringgetCustomName(){
Name;
}
}
Writethemappingfortheaction
1.
Addthemapinsideapackagethatextends"json-default"
2.
Addaresultoftype"json"
Example:
<?xmlversion="1.0"encoding="UTF-8"?>
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"/dtds/">
JSONexampleoutput
{
"field1":"str",
"ints":[10,20],
"map":{
"John":"Galt"
},
"newName":"custom"
}
JSONRPC
Thejsonplugincanbeudtoexecuteactionmethodsfromjavascriptandreturntheoutput.
ThisfeaturewasdevelopedwithDojoinmind,soitusSimpleMethodDefinitiontoadverti
'sworkitoutwithanexample(ulessasmostexamples).
Firstwritetheaction:
packagesmd;
hod;
;
publicclassSMDAction{
publicStringsmd(){
S;
}
@SMDMethod
publicBeandoSomething(Beanbean,intquantity){
ce(quantity*10);
returnbean;
}
}
MethodsthatwillbecalledremotelymustbeannotatedwiththeSMDMethodannotation,for
hodwilltakeabeanobject,ion
canbeannotatedwiththeSMDannotationtocustomizethegeneratedSMD(moreonthat
soon),ane,wehavea
"dummy",thodwillbeudtogeneratetheSimpleMethodDefinition(a
definitionofallthervicesprovidedbythisclass),usingthe"json"result.
Thebeanclass:
packagesmd;
publicclassBean{
privateStringtype;
privateintprice;
publicStringgetType(){
returntype;
}
publicvoidtType(Stringtype){
=type;
}
publicintgetPrice(){
returnprice;
}
publicvoidtPrice(intprice){
=price;
}
}
Themapping:
Nothingspecialhere,exceptthatboththeinterceptorandtheresultmustbeappliedtothe
action,and"enableSMD"mustbeenabledforboth.
Nowthejavascriptcode:
//loaddojoRPC
e(".*");
//createrviceobject(proxy)usingSMD(generatedbythejson
result)
varrvice=rvice("${smdUrl}");
//functioncalledwhenremotemethodreturns
varcallback=function(bean){
alert("Pricefor"++"is"+);
};
//parameter
varbean={type:"Mocca"};
//executeremotemethod
vardefered=thing(bean,5);
//attachcallbacktodeferedobject
lback(callback);
Dojo'sJsonServicewillmakearequesttotheactiontoloadtheSMD,whichwillreturnaJSON
objectwiththedefinitionoftheavailableremotemethods,usingthatinformationDojocreatesa
"proxy"eoftheasynchronousnatureoftherequest,whenthe
methodixecuted,adeferredobjectisreturned,towhichacallbackfunctioncanbeattached.
Thecallbac'sit.
Proxiedobjects
(V0.20)AsannotationsarenotinheritedinJava,someurmightexperienceproblemswhile
uhaveattachedAOPinterceptorstoyour
action.
Inthissituation,thepluginwillnotdetecttheannotationsonmethodsinyouraction.
Toovercomethis,tthe"ignoreInterfaces"resultparametertofal(truebydefault)to
requestthattheplugininspectsallinterfacesandsuperclassoftheactionforannotationson
theaction'smethods.
NOTE:Thisparametershouldonlybettofalifyouractioncouldbeaproxyasthereisa
performancecostcaudbyrecursionthroughtheinterfaces.
在Struts2中使用JSonajax支持
来源:作者:发布时间:2007-12-19
JSON插件提供了一种名为json的ResultType,一旦为某个Action指定了
一个类型为json的Result,则该Result无需映射到任何视图资源。因为JSON
插件会负责将Action里的状态信息序列化成JSON格式的数据,并将该数据返
回给客户端页面的JavaScript。
简单地说,JSON插件允许我们在JavaScript中异步调用Action,而且Action
不再需要使用视图资源来显示该Action里的状态信息,而是由JSON插件负责
将Action里的状态信息返回给调用页面——通过这种方式,就能够完成Ajax
交互。
Struts2提供了一种可插拔方式来管理插件,安装Struts2的JSON插件和安
装普通插件并没有太大的区别,相同只需要将Struts2插件的JAR文档复制到
Web应用的WEB-INF/lib路径下即可。
安装JSON插件按如下步骤进行:
(1)登陆/p/jsonplugin/downloads/list站点,下载Struts2
的JSON插件的最新版本,当前最新版本是0.7,我们能够下载该版本的JSON
插件。
(2)将下载到的文档复制到Web应用的WEB-INF路径
下,即可完成JSON插件的安装。
实现Actio逻辑
假设wo,en输入页面中包含了三个表单域,这三个表单域对于三个请求参
数,因此应该使用Action来封装这三个请求参数。三个表单域的name分别为
field1、field2和field3。
处理该请求的Action类代码如下:
publicclassJSONExample
{
//封装请求参数的三个属性
privateStringfield1;
privatetransientStringfield2;
privateStringfield3;
//封装处理结果的属性
privateint[]ints={10,20};
privateMapmap=newHashMap();
privateStringcustomName="custom";
//三个请求参数对应的tter和getter方法
publicStringgetField1()
{
returnfield1;
}
publicvoidtField1(Stringfield1)
{
1=field1;
}
//此处省略了field1和field2两个字段的tter和getter方法
...
//封装处理结果的属性的tter和getter方法
publicint[]getInts()
{
returnints;
}
publicvoidtInts(int[]ints)
{
=ints;
}
publicMapgetMap()
{
returnmap;
}
publicvoidtMap(Mapmap)
{
=map;
}
//使用注释语法来改变该属性序列化后的属性名
@JSON(name="newName")
publicStringgetCustomName()
{
Name;
}
publicStringexecute()
{
("name","yeeku");
S;
}
}
在上面代码中,使用了JSON注释,注释时指定了name域,name域指定
Action属性被序列化成JSON对象的属性名。除此之外,JSON注释还支持如下
几个域:
rialize:配置是否序列化该属性
derialize:配置是否反序列化该属性。
format:配置用于格式化输出、解析日期表单域的格式。例如"yyyy-MM-
dd'T'HH:mm:ss"。
配置该Action和配置普通Action存在小小的区别,应该为该Action配置
类型为json的Result。而这个Result无需配置任何视图资源。
配置该Action的文档代码如下:
<?xmlversion="1.0"encoding="GBK"?>
<!DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"/dtds/">
<struts>
<constantname="ng"value="UTF-8"/>
<packagename="example"extends="json-default">
<actionname="JSONExample"class="ample">
<resulttype="json"/>
</action>
</package>
</struts>
在上面配置文档中有两个值得注意的地方:
第一个地方是配置ng常量时,不再是使用GBK编码,而
是UTF-8编码,这是因为Ajax的POST请求都是以UTF-8的方式进行编码的。
第二个地方是配置包时,自己的包继承了json-default包,而不再继承默认
的default包,这是因为只有在该包下才有json类型的Result。
本文发布于:2022-11-15 14:33:02,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/88/24857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |