1:toJson的用法(当参数是bean对象时,将javabean转换为json数据)
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转换为json数据
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的用法(当参数是List时)
Gson gson=new Gson();
List<String> list= Arrays.asList("laoli","28","娜娜","liua");
String s=gson.toJson(list);//将List转换为json数据
Log.i("json",s.toString());
/*输出信息为:
11-16 21:13:17.575 22693-22693/com.example.liang.myapplication I/json: ["laoli","28","娜娜","liua"]*/
3:toJson的用法(当参数是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数据转换为bean,转换单条json数据)
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数据转换为bean,转换多条json数据)
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}]*/