JSON解析详细文档.docx
《JSON解析详细文档.docx》由会员分享,可在线阅读,更多相关《JSON解析详细文档.docx(23页珍藏版)》请在冰豆网上搜索。
![JSON解析详细文档.docx](https://file1.bdocx.com/fileroot1/2023-1/23/96c1e7d9-589f-4a51-9f9e-f19951bb1e41/96c1e7d9-589f-4a51-9f9e-f19951bb1e411.gif)
JSON解析详细文档
JSON的含义?
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官方网站:
http:
//www.json.org(中文内容参看:
http:
//www.json.org/json-zh.html)
GWT与JSON
GWT中支持的客户端服务器端方法调用和数据传递的标准格式是RPC。
JSON并不是GWT支持的标准的数据传递格式。
那么如何使用JSON来作为GWT的数据传递格式呢?
需要以下几步。
第一,引用HTTP和JSON支持。
第二,在客户端创建JSON数据,提交到服务器
第三,在服务器上重写数据格式解析的代码,使之支持JSON格式的数据
第四,在服务器上组织JSON格式的数据,返回给客户端。
第五,客户端解析服务器传回的JSON数据,正确的显示
引用HTTP和JSON支持
找到.gwt.xml文件,在其中的
在之后添加如下的内容:
其中com.google.gwt.json.JSON指的是要使用JSON,com.google.gwt.http.HTTP值得是通过HTTP调用服务器上的服务方法。
客户端构造JSON数据
客户端需要使用com.google.gwt.json.client包内的类来组装JSON格式的数据,数据格式如下:
数据类型
说明
JSONArray
JSONValue构成的数组类型
JSONBoolean
JSONboolean值
JSONException
访问JSON结构的数据出错的情况下可以抛出此异常
JSONNull
JSONNull根式的数据
JSONNumber
JSONNumber类型的数据
JSONObject
JSONObject类型的数据
JSONParser
将String格式的JSON数据解析为JSONValue类型的数据
JSONString
JSONString类型的数据
JSONValue
所有JSON类型值的超级类型
组合一个简单的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执行。
服务端重写数据解析代码,支持JSON格式的数据
在服务器上,需要使用JSONJava支持类才能将JSON格式的数据转换为各种类型的数据,当然也可以自己写一些解析用的代码。
这里我们使用了www.json.org上的代码来完成。
这组代码与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 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 System.out.println("item"+i+":
"+jsonArray.getString(i));
}
}catch(JSONExceptione){
e.printStackTrace(); //TochangebodyofcatchstatementuseFile|Settings|FileTemplates.
}
return"success";
}
}
在服务器上组织JSON格式的数据,返回给客户端
同上
客户端解析服务器传回的JSON数据,正确的显示
同上
Struts2返回json需要jsonplugin-0[1].25的包
然后我们的配置文件中需要继承json-default
Java代码
1.
xml version="1.0" encoding="UTF-8" ?
>
2.
DOCTYPE struts PUBLIC
3. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4. "http:
//struts.apache.org/dtds/struts-2.0.dtd">
5.
6.
7.
8.
9.
10.
11.
12.
-- Add actions here -->
13.
14.
xmlversion="1.0"encoding="UTF-8"?
>
DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.0//EN"
"http:
//struts.apache.org/dtds/struts-2.0.dtd">
--Addactionshere-->
然后我们的Action中需要返回的json信息需要加上注解
Java代码
1.//pizza
2.package com.action.testJson;
3.
4.import java.util.ArrayList;
5.import java.util.List;
6.
7.import com.googlecode.jsonplugin.annotations.JSON;
8.import com.opensymphony.xwork2.ActionSupport;
9.
10.public class JsonAction extends ActionSupport {
11.
12. private static final long serialVersionUID = -4082165361641669835L;
13.
14. Users user=new Users();
15. List userList=new ArrayList();
16.
17.
18. public String testUser(){
19. System.out.println("in the json Acton");
20. userInit();
21. userList.add(user);
22. return SUCCESS;
23. }
24.
25. public void userInit(){
26. user.setAge
(1);
27. user.setName("张泽峰");
28. user.setPassword("nofengPassword");
29. }
30.
31. @JSON(name="userString")
32. public Users getUser() {
33. return user;
34. }
35.
36. @JSON(name="userList")
37. public List getUserList() {
38. return userList;
39. }
40.
41. public void setUser(Users user) {
42. this.user = user;
43. }
44.
45. public void setUserList(List userList) {
46. this.userList = userList;
47. }
48.
49.
50.}
JSONPlugin
的说明
EditPage
BrowseSpace
AddPage
AddNews
AddedbyMusachyBarroso,lasteditedbyghostrolleronJul04,2008 (viewchange)showcommenthidecomment
Comment:
change"ignoreInterfaces"to"ignoreSMDMethodInterfaces"ininterceptorparameters
Viewpagehistory
Name
JSONPlugin
Publisher
MusachyBarroso
License
OpenSource(ASL2)
Version
0.30
Compatibility
Struts2.0.6orlater
Homepage
Download
rate-34268-90672
Rating?
∙1
∙2
∙3
∙4
∙5
Overview
TheJSONpluginprovidesa"json"resulttypethatserializesactionsintoJSON.Theserializationprocessisrecursive,meaningthatthewholeobjectgraph,startingontheactionclass(baseclassnotincluded)willbeserialized(rootobjectcanbecustomizedusingthe"root"attribute).Iftheinterceptorisused,theactionwillbepopulatedfromtheJSONcontentintherequest,thesearetherulesoftheinterceptor:
1.The"content-type"mustbe"application/json"
2.TheJSONcontentmustbewellformed,seejson.org
forgrammar.
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.
Installation
Thisplugincanbeinstalledbycopyingthepluginjarintoyourapplication's/WEB-INF/libdirectory.Nootherfilesneedtobecopiedorcreated.
Tousemaven,addthistoyourpom:
...
com.googlecode
jsonplugin
0.26
...
MavenPluginRepository
http:
//struts2plugin-maven-
false
true
CustomizingSerializationandDeserialization
UsetheJSONannotationtocustomizetheserialization/deserializationprocess.AvailableJSONannotationfields:
Name
Description
DefaultValue
Serialization
Deserialization
name
Customizefieldname
empty
yes
no
serialize
Includeinserialization
true
yes
no
deseri