JSON

JSON教程免费下载

字号+ 作者:H5之家 来源:H5之家 2017-04-16 14:00 我要评论( )

JSON教程,JSON教程免费下载:JSONJSONJSONJSON是什么?JSON的全称是JavaScriptObjectNotation是一种轻量级的数据交换格式。JSON与XML具有相同的

JSON教程.pdf JSON教程.pdf

简介:前端开发必备工具

JSONJSONJSONJSON是什么?JSON的全称是JavaScriptObjectNotation,是一种轻量级的数据交换格式。JSON与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官方网站:(中文内容参看:)GWTGWTGWTGWT与JSONJSONJSONJSONGWT中支持的客户端服务器端方法调用和数据传递的标准格式是RPC。JSON并不是GWT支持的标准的数据传递格式。那么如何使用JSON来作为GWT的数据传递格式呢?需要以下几步。第一,引用HTTP和JSON支持。第二,在客户端创建JSON数据,提交到服务器第三,在服务器上重写数据格式解析的代码,使之支持JSON格式的数据第四,在服务器上组织JSON格式的数据,返回给客户端。第五,客户端解析服务器传回的JSON数据,正确的显示引用HTTPHTTPHTTPHTTP和JSONJSONJSONJSON支持找到.gwt.xml文件,在其中的<inheritsname='com.google.gwt.user.User'/>在之后添加如下的内容:<inheritsname="com.google.gwt.json.JSON"/><inheritsname="com.google.gwt.http.HTTP"/>其中com.google.gwt.json.JSON指的是要使用JSON,com.google.gwt.http.HTTP值得是通过HTTP调用服务器上的服务方法。客户端构造JSONJSONJSONJSON数据客户端需要使用com.google.gwt.json.client包内的类来组装JSON格式的数据,数据格式如下:组合一个简单的JSON数据:数据类型说明JSONArrayJSONValue构成的数组类型JSONBooleanJSONboolean值JSONException访问JSON结构的数据出错的情况下可以抛出此异常JSONNullJSONNull根式的数据JSONNumberJSONNumber类型的数据JSONObjectJSONObject类型的数据JSONParser将String格式的JSON数据解析为JSONValue类型的数据JSONStringJSONString类型的数据JSONValue所有JSON类型值的超级类型JSONObjectinput=newJSONObject();JSONStringvalue=newJSONString("mazhao");input.put("name",value);JSON数据格式为:{name:"mazhao"}组合一个包含数组类型的复杂JSON数据:JSONObjectinput=newJSONObject();JSONStringvalue=newJSONString("mazhao");input.put("name",value);JSONArrayarrayValue=newJSONArray();arrayValue.set(0,newJSONString("arrayitem0"));arrayValue.set(1,newJSONString("arrayitem1"));arrayValue.set(2,newJSONString("arrayitem2"));input.put("array",arrayValue);JSON数据格式为:{name:"mazhao",array:{"arrayitem0","arrayitem1","arrayitem2"}}注意上述的JSON类型的数据,使用的都是com.google.gwt.json.client包内的类型。这些类型最终会被编译为JavaScript执行。服务端重写数据解析代码,支持JSONJSONJSONJSON格式的数据在服务器上,需要使用JSONJava支持类才能将JSON格式的数据转换为各种类型的数据,当然也可以自己写一些解析用的代码。这里我们使用了上的代码来完成。这组代码与com.google.gwt.json.client的代码很相似,只是在org.json包内部。怎么解析JSON术诀呢?针对上述中的复杂的JSON数据:{name:"mazhao",array:{"arrayitem0","arrayitem1","arrayitem2"}}可以使用如下的方式解析:JSONObjectjsonObject=newJSONObject(payload);Stringname=jsonObject.getString("name");System.out.println("nameis:"+name);JSONArrayjsonArray=jsonObject.getJSONArray("array");for(inti=0;i<jsonArray.length();i++){System.out.println("item"+i+":"+jsonArray.getString(i));}其中payload指的是上述的JSON格式的数据。那么如何写GWT的Service来得到Payload的数据呢?需要两点,第一,需要建立一个Service类,第二,覆盖父类的processCall方法。示例代码:packagecom.jpleasure.gwt.json.server;importcom.google.gwt.user.client.rpc.SerializationException;importcom.google.gwt.user.server.rpc.RemoteServiceServlet;importcom.jpleasure.gwt.json.client.HelloWorldService;importorg.json.JSONArray;importorg.json.JSONException;importorg.json.JSONObject;/***CreatedbyIntelliJIDEA.*User:vaio*Date:2007-9-4*Time:22:08:31*TochangethistemplateuseFile|Settings|FileTemplates.*/publicclassHelloWorldServiceImplextendsRemoteServiceServletimplementsHelloWorldService{publicStringprocessCall(Stringpayload)throwsSerializationException{try{JSONObjectjsonObject=newJSONObject(payload);Stringname=jsonObject.getString("name");System.out.println("nameis:"+name);JSONArrayjsonArray=jsonObject.getJSONArray("array");for(inti=0;i<jsonArray.length();i++){System.out.println("item"+i+":"+jsonArray.getString(i));}}catch(JSONExceptione){e.printStackTrace();//TochangebodyofcatchstatementuseFile|Settings|FileTemplates.}return"success";}}在服务器上组织JSONJSONJSONJSON格式的数据,返回给客户端同上客户端解析服务器传回的JSONJSONJSONJSON数据,正确的显示同上Struts2Struts2Struts2Struts2返回jsonjsonjsonjson需要jsonplugin-0[1].25jsonplugin-0[1].25jsonplugin-0[1].25jsonplugin-0[1].25的包然后我们的配置文件中需要继承json-defaultJava代码1.<?xmlversion="1.0"encoding="UTF-8"?>2.<!DOCTYPEstrutsPUBLIC3."-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"4."">5.6.<struts>7.8.<packagename="com.action.testJson"extends="json-default"namespace="/">9.<actionname="jsonUser"class="com.action.testJson.JsonAction"method="testUser">10.<resulttype="json"/>11.</action>12.<!--Addactionshere-->13.</package>14.</struts><?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEstrutsPUBLIC"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"""><struts><packagename="com.action.testJson"extends="json-default"namespace="/"><actionname="jsonUser"class="com.action.testJson.JsonAction"method="testUser"><resulttype="json"/></action><!--Addactionshere--></package></struts>然后我们的Action中需要返回的json信息需要加上注解Java代码1.//pizza2.packagecom.action.testJson;3.4.importjava.util.ArrayList;5.importjava.util.List;6.7.importcom.googlecode.jsonplugin.annotations.JSON;8.importcom.opensymphony.xwork2.ActionSupport;9.10.publicclassJsonActionextendsActionSupport{11.12.privatestaticfinallongserialVersionUID=-4082165361641669835L;13.14.Usersuser=newUsers();15.ListuserList=newArrayList();16.17.18.publicStringtestUser(){19.System.out.println("inthejsonActon");20.userInit();21.userList.add(user);22.returnSUCCESS;23.}24.25.publicvoiduserInit(){26.user.setAge(1);27.user.setName("张泽峰");28.user.setPassword("nofengPassword");29.}30.31.@JSON(name="userString")32.publicUsersgetUser(){33.returnuser;34.}35.36.@JSON(name="userList")37.publicListgetUserList(){38.returnuserList;39.}40.41.publicvoidsetUser(Usersuser){42.this.user=user;43.}44.45.publicvoidsetUserList(ListuserList){46.this.userList=userList;47.}48.49.50.}JSONJSONJSONJSONPluginPluginPluginPlugin的说明EditPageBrowseSpaceAddPageAddNewsAddedbyMusachyBarroso,lasteditedbyghostrolleronJul04,2008(viewchange)SHOWCOMMENTNameNameNameNameJSONPluginPublisherPublisherPublisherPublisherMusachyBarrosoLicenseLicenseLicenseLicenseOpenSource(ASL2)VersionVersionVersionVersion0.30CompatibilityCompatibilityCompatibilityCompatibilityStruts2.0.6orlaterHomepageHomepageHomepageHomepage://code.google.com/p/jsonplugin/downloads/listOverviewOverviewOverviewOverviewTheJSONpluginprovidesa"json"resulttypethatserializesactionsintoJSON.Theserializationprocessisrecursive,meaningthatthewholeobjectgraph,startingontheactionclass(baseclassnotincluded)willbeserialized(rootobjectcanbecustomizedusingthe"root"attribute).Iftheinterceptorisused,theactionwillbepopulatedfromtheJSONcontentintherequest,thesearetherulesoftheinterceptor:1.The"content-type"mustbe"application/json"2.TheJSONcontentmustbewellformed,seejson.orgforgrammar.3.Actionmusthaveapublic"setter"methodforfieldsthatmustbepopulated.4.Supportedtypesforpopulationare:Primitives(int,long...String),Date,List,Map,PrimitiveArrays,Otherclass(moreonthislater),andArrayofOtherclass.5.AnyobjectinJSON,thatistobepopulatedinsidealist,oramap,willbeoftypeMap(mappingfrompropertiestovalues),anywholenumberwillbeoftypeLong,anydecimalnumberwillbeoftypeDouble,andanyarrayoftypeList.GiventhisJSONstring:{"doubleValue":10.10,"nestedBean":{"name":"MrBean"},"list":["A",10,20.20,{"firstName":"ElZorro"}],"array":[10,20]}Theactionmusthavea"setDoubleValue"method,takingeithera"float"ora"double"argument(theinterceptorwillconvertthevaluetotherightone).Theremustbea"setNestedBean"whoseargumenttypecanbeanyclass,thathasa"setName"methodtakingasargumentan"String".Theremustbea"setList"methodthattakesa"List"asargument,thatlistwillcontain:"A"(String),10(Long),20.20(Double),Map("firstName"->"ElZorro").The"setArray"methodcantakeasparametereithera"List",oranynumericarray.Rating?11112222333344445555InstallationInstallationInstallationInstallationThisplugincanbeinstalledbycopyingthepluginjarintoyourapplication's/WEB-INF/libdirectory.Nootherfilesneedtobecopiedorcreated.Tousemaven,addthistoyourpom:<dependencies>...<dependency><groupId>com.googlecode</groupId><artifactId>jsonplugin</artifactId><version>0.26</version></dependency>...</dependencies><repository><id>MavenPluginRepository</id><url></url><snapshots><enabled>false</enabled></snapshots><releases><enabled>true</enabled></releases></repository>CustomizingCustomizingCustomizingCustomizingSerializationSerializationSerializationSerializationandandandandDeserializationDeserializationDeserializationDeserializationUsetheJSONannotationtocustomizetheserialization/deserializationprocess.AvailableJSONannotationfields:NameNameNameNameDescriptionDescriptionDescriptionDescriptionDefaultDefaultDefaultDefaultValueValueValueValueSerializationSerializationSerializationSerializationDeserializationDeserializationDeserializationDeserializationnameCustomizefieldnameemptyyesnoserializeIncludeinserializationtrueyesnodeserializeIncludeindeserializationtruenoyesExcludingExcludingExcludingExcludingpropertiespropertiespropertiespropertiesAcomma-delimitedlistofregularexpressionscanbepassedtotheJSONResultandInterceptor,propertiesmatchinganyoftheseregularexpressionswillbeignoredontheserializationprocess:<!--Resultfragment--><resulttype="json"><paramname="excludeProperties">login.password,studentList.*\.sin</param></result><!--Interceptorfragment--><interceptor-refname="json"><paramname="enableSMD">true</param><paramname="excludeProperties">login.password,studentList.*\.sin</param></interceptor-ref>IncludingIncludingIncludingIncludingpropertiespropertiespropertiespropertiesAcomma-delimitedlistofregularexpressionscanbepassedtotheJSONResulttorestrictwhichpropertieswillbeserialized.ONLYpropertiesmatchinganyoftheseregularexpressionswillbeincludedintheserializedoutput.<!--Resultfragment--><resulttype="json"><paramname="includeProperties">^entries\[\d+\]\.clientNumber,formatFormatusedtoformat/parseaDatefield"yyyy-MM-dd'T'HH:mm:ss"yesyesNoteNoteNoteNoteExcludepropertyexpressionstakeprecedenceoverincludepropertyexpressions.Thatis,ifyouuseincludeandexcludepropertyexpressionsonthesameresult,includepropertyexpressionswillnotbeappliedifanexcludeexcludepropertyexpressionmatchesapropertyfirst.^entries\[\d+\]\.scheduleNumber,^entries\[\d+\]\.createUserId</param></result>RootRootRootRootObjectObjectObjectObjectUsethe"root"attribute(OGNLexpression)tospecifytherootobjecttobeserialized.<resulttype="json"><paramname="root">person.job</param></result>The"root"attribute(OGNLexpression)canalsobeusedontheinterceptortospecifytheobjectthatmustbepopulated,makemakemakemakesuresuresuresurethisthisthisthisobjectobjectobjectobjectisisisisnotnotnotnotnullnullnullnull.<interceptor-refname="json"><paramname="root">bean1.bean2</param></interceptor-ref>WrapWrapWrapWrapwithwithwithwithCommentsCommentsCommentsCommentsIfthe"wrapWithComments"(falsebydefault)attributeissettotrue,thegeneratedJSONiswrappedwithcommentslike:/*{"doubleVal":10.10,"nestedBean":{"name":"MrBean"},"list":["A",10,20.20,{"firstName":"ElZorro"}],"array":[10,20]}*/wrapWithCommentscanturnsafeJSONtextintodangeroustext.Forexample,["*/alert('XSS');/*"]ThankstoDouglasCrockfordforthetip!ThiscanbeusedtoavoidpotentialJavascriptHijacks.Tostripthosecommentsuse:varresponseObject=eval("("+data.substring(data.indexOf("\/\*")+2,data.lastIndexOf("\*\/"))+")");BaseBaseBaseBaseClassesClassesClassesClassesBydefaultpropertiesdefinedonbaseclassesofthe"root"objectwon'tbeserialized,toserializepropertiesinallbaseclasses(uptoObject)set"ignoreHierarchy"tofalseintheJSONresult:<resulttype="json"><paramname="ignoreHierarchy">false</param></result>EnumerationsEnumerationsEnumerationsEnumerationsBydefault,anEnumisserializedasaname=valuepairwherevalue=name().publicenumAnEnum{ValueA,ValueB}JSON:"myEnum":"ValueA"Usethe"enumAsBean"resultparametertoserializeEnum'sasabeanwithaspecialproperty_namewithvaluename().Allpropertiesoftheenumarealsoserialized.publicenumAnEnum{ValueA("A"),ValueB("B");privateStringval;publicAnEnum(val){this.val=val;}publicgetVal(){returnval;}}JSON:myEnum:{"_name":"ValueA","val":"A"}Enablethisparameterthroughstruts.xml:<resulttype="json"><paramname="enumAsBean">true</param></result>CompressingCompressingCompressingCompressingthethethetheoutput.output.output.output.SettheenableGZIPattributetotruetogzipthegeneratedjsonresponse.Therequestmustmustmustmustinclude"gzip"inthe"Accept-Encoding"headerforthistowork.<resulttype="json"><paramname="enableGZIP">true</param></result>ExampleExampleExampleExampleSetupSetupSetupSetupActionActionActionActionThissimpleactionhassomefields:Example:importjava.util.HashMap;importjava.util.Map;importcom.opensymphony.xwork2.Action;publicclassJSONExample{privateStringfield1="str";privateint[]ints={10,20};privateMapmap=newHashMap();privateStringcustomName="custom";//'transient'fieldsarenotserializedprivatetransientStringfield2;//fieldswithoutgettermethodarenotserializedprivateStringfield3;publicStringexecute(){map.put("John","Galt");returnAction.SUCCESS;}publicStringgetField1(){returnfield1;}publicvoidsetField1(Stringfield1){this.field1=field1;}publicint[]getInts(){returnints;}publicvoidsetInts(int[]ints){this.ints=ints;}publicMapgetMap(){returnmap;}publicvoidsetMap(Mapmap){this.map=map;}@JSON(name="newName")publicStringgetCustomName(){returnthis.customName;}}WriteWriteWriteWritethethethethemappingmappingmappingmappingforforforforthethethetheactionactionactionaction1.Addthemapinsideapackagethatextends"json-default"2.Addaresultoftype"json"Example:<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEstrutsPUBLIC"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"""><struts><packagename="example"extends="json-default"><actionname="JSONExample"class="example.JSONExample"><resulttype="json"/></action></package></struts>JSONJSONJSONJSONexampleexampleexampleexampleoutputoutputoutputoutput{"field1":"str","ints":[10,20],"map":{"John":"Galt"},"newName":"custom"}JSONJSONJSONJSONRPCRPCRPCRPCThejsonplugincanbeusedtoexecuteactionmethodsfromjavascriptandreturntheoutput.ThisfeaturewasdevelopedwithDojoinmind,soitusesSimpleMethodDefinitiontoadvertisetheremoteservice.Let'sworkitoutwithanexample(uselessasmostexamples).Firstwritetheaction:packagesmd;importcom.googlecode.jsonplugin.annotations.SMDMethod;importcom.opensymphony.xwork2.Action;publicclassSMDAction{publicStringsmd(){returnAction.SUCCESS;}@SMDMethodpublicBeandoSomething(Beanbean,intquantity){bean.setPrice(quantity*10);returnbean;}}MethodsthatwillbecalledremotelymustmustmustmustbeannotatedwiththeSMDMethodannotation,forsecurityreasons.Themethodwilltakeabeanobject,modifyitspriceandreturnit.TheactioncanbeannotatedwiththeSMDannotationtocustomizethegeneratedSMD(moreonthatsoon),andparameterscanbeannotatedwithSMDMethodParameter.Asyoucansee,wehavea"dummy",smdmethod.ThismethodwillbeusedtogeneratetheSimpleMethodDefinition(adefinitionofalltheservicesprovidedbythisclass),usingthe"json"result.Thebeanclass:packagesmd;publicclassBean{privateStringtype;privateintprice;publicStringgetType(){returntype;}publicvoidsetType(Stringtype){this.type=type;}publicintgetPrice(){returnprice;}publicvoidsetPrice(intprice){this.price=price;}}Themapping:<packagename="RPC"namespace="/nodecorate"extends="json-default"><actionname="SMDAction"class="smd.SMDAction"method="smd"><interceptor-refname="json"><paramname="enableSMD">true</param></interceptor-ref><resulttype="json"><paramname="enableSMD">true</param></result></action></package>Nothingspecialhere,exceptthatbothbothbothboththeinterceptorandtheresultmustbeappliedtotheaction,and"enableSMD"mustbeenabledforboth.Nowthejavascriptcode:<s:urlid="smdUrl"namespace="/nodecorate"action="SMDAction"/><scripttype="text/javascript">//loaddojoRPCdojo.require("dojo.rpc.*");//createserviceobject(proxy)usingSMD(generatedbythejsonresult)varservice=newdojo.rpc.JsonService("${smdUrl}");//functioncalledwhenremotemethodreturnsvarcallback=function(bean){alert("Pricefor"+bean.type+"is"+bean.price);};//parametervarbean={type:"Mocca"};//executeremotemethodvardefered=service.doSomething(bean,5);//attachcallbacktodeferedobjectdefered.addCallback(callback);</script>Dojo'sJsonServicewillmakearequesttotheactiontoloadtheSMD,whichwillreturnaJSONobjectwiththedefinitionoftheavailableremotemethods,usingthatinformationDojocreatesa"proxy"forthosemethods.Becauseoftheasynchronousnatureoftherequest,whenthemethodisexecuted,adeferredobjectisreturned,towhichacallbackfunctioncanbeattached.Thecallbackfunctionwillreceiveasaparametertheobjectreturnedfromyouraction.That'sit.ProxiedProxiedProxiedProxiedobjectsobjectsobjectsobjects(V0.20)AsannotationsarenotinheritedinJava,someusermightexperienceproblemswhiletryingtoserializeobjectsthatareproxied.eg.whenyouhaveattachedAOPinterceptorstoyouraction.Inthissituation,thepluginwillnotdetecttheannotationsonmethodsinyouraction.Toovercomethis,setthe"ignoreInterfaces"resultparametertofalse(truebydefault)torequestthattheplugininspectsallinterfacesandsuperclassesoftheactionforannotationsontheaction'smethods.NOTE:Thisparametershouldonlybesettofalseifyouractioncouldbeaproxyasthereisaperformancecostcausedbyrecursionthroughtheinterfaces.<actionname="contact"class="package.ContactAction"method="smd"><interceptor-refname="json"><paramname="enableSMD">true</param><paramname="ignoreSMDMethodInterfaces">false</param></interceptor-ref><resulttype="json"><paramname="enableSMD">true</param><paramname="ignoreInterfaces">false</param></result><interceptor-refname="default"/></action>在StrutsStrutsStrutsStruts2222中使用JSonJSonJSonJSonajaxajaxajaxajax支持来源:作者:发布时间:2007-12-19JSON插件提供了一种名为json的ResultType,一旦为某个Action指定了一个类型为json的

下载资料到本地,随时随地想用就用!

所需积分:2分,104人已下载

JSON教程.pdf JSON教程.pdf

简介:前端开发必备工具

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • json教程 鸡年春节863万人陕西博物馆里感受中华文明

    json教程 鸡年春节863万人陕西博物馆里感受中华文明

    2017-02-11 08:01

  • (转载)JSON教程

    (转载)JSON教程

    2017-02-03 13:01

  • json教程系列(5)-json错误解析net.sf.ezmorph.bean.MorphDynaBean cannot

    json教程系列(5)-json错误解析net.sf.ezmorph.bean.MorphDynaBean

    2017-01-31 16:02

  • 易语言解析JSON教程

    易语言解析JSON教程

    2017-01-30 15:00

网友点评