1:toJson的用法(當(dāng)參數(shù)是bean對象時匾二,將javabean轉(zhuǎn)換為json數(shù)據(jù))
Gson gson=new Gson();
xuesheng xuesheng[]={new xuesheng("laoj",10,99),new xuesheng("laoja",33,11),new xuesheng("laowang",99,12)};
String s=gson.toJson(xuesheng);//將javabean轉(zhuǎn)換為json數(shù)據(jù)
Log.i("json",s.toString());
/*輸出信息為:
11-16 21:03:07.485 11317-11317/com.example.liang.myapplication I/json: [{"name":"laoj","score":99.0,"xuehao":10},{"name":"laoja","score":11.0,"xuehao":33},{"name":"laowang","score":12.0,"xuehao":99}]*/
bean文件為:
public class xuesheng
{
private String name;
private int xuehao;
private float score;
public xuesheng() {
}
public xuesheng(String name, int xuehao, float score) {
this.name = name;
this.xuehao = xuehao;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getXuehao() {
return xuehao;
}
public void setXuehao(int xuehao) {
this.xuehao = xuehao;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
@Override
public String toString() {
return "xuesheng{" +
"name='" + name + "'" +
", xuehao=" + xuehao +
", score=" + score +
'}';
}
}
2:toJson的用法(當(dāng)參數(shù)是List時)
Gson gson=new Gson();
List<String> list= Arrays.asList("laoli","28","娜娜","liua");
String s=gson.toJson(list);//將List轉(zhuǎn)換為json數(shù)據(jù)
Log.i("json",s.toString());
/*輸出信息為:
11-16 21:13:17.575 22693-22693/com.example.liang.myapplication I/json: ["laoli","28","娜娜","liua"]*/
3:toJson的用法(當(dāng)參數(shù)是Map時)
Gson gson=new Gson();
Map<String,Object> map=new HashMap<>();
map.put("name","laowang");
map.put("age",20);
map.put("school","mazhong");
Log.i("xinxi",gson.toJson(map));
/*輸出信息為:
11-16 21:17:25.615 27567-27567/com.example.liang.myapplication I/xinxi: {"name":"laowang","age":20,"school":"mazhong"}*/
4:fromJson的用法(將json數(shù)據(jù)轉(zhuǎn)換為bean,轉(zhuǎn)換單條json數(shù)據(jù))
Gson gson=new Gson();
String studentJsonStr="{\"name\":\"xuanyouwu\",\"xuehao\":100,\"score\":26}";
xuesheng xuesheng=gson.fromJson(studentJsonStr,xuesheng.class);
Log.i("xingxi",xuesheng.toString());
/*輸出信息為:
11-16 21:23:36.095 3735-3735/com.example.liang.myapplication I/xingxi: xuesheng{name='xuanyouwu', xuehao=100, score=26.0}*/
5:fromJson的用法(將json數(shù)據(jù)轉(zhuǎn)換為bean,轉(zhuǎn)換多條json數(shù)據(jù))
Gson gson=new Gson();
String studentJsonStr="[{\"name\":\"xuanyouwu\",\"xuehao\":100,\"score\":26},{\"name\":\"laofu\",\"xuehao\":200,\"score\":216},{\"name\":\"laoliang\",\"xuehao\":10,\"score\":6}]";
List<xuesheng> xuesheng=gson.fromJson(studentJsonStr,new TypeToken<List<xuesheng>>(){}.getType());
Log.i("xingxi",xuesheng.toString());
/*輸出信息為:
11-16 21:28:53.855 10282-10282/com.example.liang.myapplication I/xingxi: [xuesheng{name='xuanyouwu', xuehao=100, score=26.0}, xuesheng{name='laofu', xuehao=200, score=216.0}, xuesheng{name='laoliang', xuehao=10, score=6.0}]*/