Gson入門ノート
3097 ワード
この文章はただ簡単な例で、自分でまとめて使うものです。詳細な資料が必要な場合は、Gson APIドキュメントを参照してください。
最近のプロジェクトでは異なる言語間のインターフェースの呼び出しに関連しています。最後にJsonをデータ形式として選択します。JavaでGoogleのGsonを選択しました。なぜか分かりません。
先にテストクラスを定義します。
簡単な説明:一つのPeope類、一つのFriend類。Friend継承People
最近のプロジェクトでは異なる言語間のインターフェースの呼び出しに関連しています。最後にJsonをデータ形式として選択します。JavaでGoogleのGsonを選択しました。なぜか分かりません。
先にテストクラスを定義します。
簡単な説明:一つのPeope類、一つのFriend類。Friend継承People
class People{
public People(){}
String Name;
String Age;
String Sex;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
Age = age;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
ArrayList<Friend> friends;
public ArrayList<Friend> getFriends() {
return friends;
}
public void setFriends(ArrayList<Friend> friends) {
this.friends = friends;
}
}
class Friend extends People{
Boolean IsGrilFriend;
public Boolean getIsGrilFriend() {
return IsGrilFriend;
}
public void setIsGrilFriend(Boolean isGrilFriend) {
IsGrilFriend = isGrilFriend;
}
}
テストコード:/**
* @param args
*/
public static void main(String[] args) {
People people = new People();
people.setName("Tom");
people.setAge("12");
people.setSex(" ");
ArrayList<Friend> _Friends = new ArrayList<Friend>();
Friend _Friend = new Friend();
_Friend.setName("Shit");
_Friend.setAge("11");
_Friend.setSex(" ");
_Friend.setIsGrilFriend(true);
_Friends.add(_Friend);
people.setFriends(_Friends);
Gson gson = new GsonBuilder().create();
long Time1 = System.currentTimeMillis();
String sResultString = gson.toJson(people,people.getClass());
long Time2 = System.currentTimeMillis();
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println(sResultString);
System.out.println(" :"+(Time2-Time1));
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
Time1 = System.currentTimeMillis();
People _Peoples = gson.fromJson(sResultString,people.getClass());
Time2 = System.currentTimeMillis();
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println(_Peoples.friends.size());
System.out.println(" :"+(Time2-Time1));
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
}
注:Gsonオブジェクトを宣言する2つの方法: Gson gson = new GsonBuilder().create();
Gson gson = new Gson();
結果:+++++++++++++++++++++++++++++++++++++++++++++++++
{"Name":"Tom","Age":"12","Sex":" ","friends":[{"IsGrilFriend":true,"Name":"Shit","Age":"11","Sex":" "}]}
:110
+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++
1
:11
+++++++++++++++++++++++++++++++++++++++++++++++++
はい、いい紹介もないです。入門するだけです。ここに書きましょう。