Gson把Java POJO和Json数据字符串之间相互转换
例如:
POJO pojo = new POJO();
pojo.name = "zhangphil";
pojo.id = 1;
pojo.strings = new ArrayList<>();
pojo.setBlog("zhangphil @ csdn");
for (int i = 0; i < 10; i++) {
pojo.strings.add(String.valueOf(i));
}
Gson gson = new Gson();
String s = gson.toJson(pojo);
Log.d("POJO转换为Json字符串", s);
POJO pojo2 = gson.fromJson(s, POJO.class);
Log.d("Json字符串转换为POJO", pojo2.name + " , " + pojo2.id + " , " + pojo2.getBlog() + " , " + pojo2.strings.size());
POJO:
private class POJO {
public String name;
public int id;
public ArrayList<String> strings;
//私有变量也可以,但是要写好get和set方法
private String blog;
public void setBlog(String blog) {
this.blog = blog;
}
public String getBlog() {
return blog;
}
}
private class POJO {
public String name;
public int id;
public ArrayList<String> strings;
//私有变量也可以,但是要写好get和set方法
private String blog;
public void setBlog(String blog) {
this.blog = blog;
}
public String getBlog() {
return blog;
}
}
利用POJO和Json字符串之间可以相互转换的便利,可以在Android的Activity以及Fragment在跳转时候传递数据。传给Bundle或Intent字符串,然后用Gson恢复出来POJO。