JSON目前慢慢的興起,也有人鼓吹取代複雜的XML格式,因此我在這次的專案中即使用JSON,也順便記錄一下。
JSON的英文官網,JSON的中文網頁
要在Java使用JSON必須要使JSON-lib。
在開始使用之前還必須要一些其他的lib配合:
- Apache-commons-beanutils
- Apache-commons-collections
- Apache-commons-lang
- Apache-commons-logging
- EZMorph
而EZMorph本來就是負責JSON-lib裏物件的轉換,現在獨立成一個專案,EZMorph可以進行基本型別(Primitive)、物件(Object)及多維度的資料轉換等等...
現在有一個Member物件,程式如下
public class Member
{
private String memberAccount;
private String memberPassword;
private String mailAddress;
private String mobilePhone;
private Integer activeType;
public String getMemberAccount() {
return memberAccount;
}
public void setMemberAccount(String memberAccount) {
this.memberAccount = memberAccount;
}
public String getMemberPassword() {
return memberPassword;
}
public void setMemberPassword(String memberPassword) {
this.memberPassword = memberPassword;
}
public String getMailAddress() {
return mailAddress;
}
public void setMailAddress(String mailAddress) {
this.mailAddress = mailAddress;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public Integer getActiveType() {
return activeType;
}
public void setActiveType(Integer activeType) {
this.activeType = activeType;
}
public String toString()
{
return "memberAccount = " + this.memberAccount + "\n" +
"memberPassword = " + this.memberPassword + "\n" +
"memberMailAddress = " + this.mailAddress + "\n" +
"memberMobilePhone = " + this.mobilePhone + "\n" +
"memberActiveType = " + this.activeType;
}
}
JSON有獨特的書寫格式如下:
{
memberAccount:"15320",
memberPassword: "234567",
mailAddress: "gh@ebsbu.com",
mobilePhone:"13587344829",
activeType: "1"
}
下面看個範例
public class JsonTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String jsonStr = "{memberAccount: \"15320\"," +
"memberPassword: \"234567\"," +
"mailAddress: \"gh@ebsbu.com\"," +
"mobilePhone: \"13587344829\"," +
"activeType: \"1\"}";
//建立JSON物件
JSONObject jsonObj = JSONObject.fromObject(jsonStr);
//透過JSONArray印出JSON的內容
System.out.println("jsonArray = " + JSONArray.fromObject(jsonObj));
//將JSONObject轉換給Member物件(用複製的說法會較為洽當)
Member member = (Member)JSONObject.toBean(jsonObj, Member.class);
System.out.println("member = " + member.toString());
}
}
看起來很簡單吧!其實JSON也是字串,主要就是利用JSONObject轉換成JSON物件,如果要看內容的話利用JSONArray印出,最後在利用JSONObject.toBean(....)轉換給Java物件。
在我這次的專案中已經成功的與RestFul結合,透過RestFul與JSON讓JAVA與.NET平台溝通,寫法也很簡單,大家都可以試試。
沒有留言:
張貼留言