Gson的使用用例

User.java

package com.stujs.po;

publicclassUser{

privateStringname;

privateStringaddress;

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

publicStringgetAddress(){

returnaddress;

}

publicvoidsetAddress(Stringaddress){

this.address=address;

}

}

StuGSON.java

package com.stujs.gson;

importorg.junit.Test;

importcom.google.gson.Gson;

importcom.stujs.po.User;

publicclassStuGSON{

@Test

publicvoidtest2JSON(){

Useruser=newUser();

user.setName("ganett");

user.setAddress("NBA");

Gsongson=newGson();

StringuserJson=gson.toJson(user);

System.out.println(userJson);

}

@Test

publicvoidtest2Object(){

StringuserJson="{'name':'hchzh','address':'China'}";

Gsongson=newGson();

Useruser=gson.fromJson(userJson,User.class);

System.out.println("Name-----"+user.getName());

System.out.println("Address-----"+user.getAddress());

}

}

相关推荐