准备工作
GSON下载地址:http://download.youkuaiyun.com/detail/wiseclown/9496184
官网地址:https://github.com/google/gson
JavaBean(自定义):
public class Student {
private String id;
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
读JSON数据
//单个对象
String json = "{\"id\":\"0001\",\"name\":\"zs\",\"sex\":\"male\"}";
Gson gson = new Gson();
Student student = gson.fromJson(json,Student.class);
//多个对象json数组
String json = "[{\"id\":\"0001\",\"name\":\"zs\",\"sex\":\"male\"},
{\"id\":\"0002\",\"name\":\"ls\",\"sex\":\"male\"}]";
Gson gson = new Gson();
List<Student> studentList = gson.fromJson(json,new TypeToken<List<Student>)(){}.getType();
从文件中读取JSON数据
student2.json
[{“id”:”000001”,”name”:”wz”,”sex”:”male”},
{“id”:”000002”,”name”:”zs”,”sex”:”male”},
{“id”:”000003”,”name”:”wf”,”sex”:”female”}
]
File file = new File(Environment.getExternalStorageDirectory(),"student2.json");
Gson gson = new Gson();
try{
List<Student> studentList = gson.fromJson(new
InputStreamReader(new FileInputStream(file)),new
TypeToken<List<Student>(){}.getType());
}catch(FileNotFoundException e){
e.printStackTrace();
}
将JSON数据写入文件中
Student student = new Student();
student.setId("1");
student.setName("wz");
student.setSex("male");
Gson gson = new Gson();
String jsonStr = gson.toJson(student);
File file = new File(Environment.getExternalStorageDirectory(),"student.json");
try{
FileOutputStream out = new FileOutputStream(file);
out.write(jsonStr.getBytes("UTF-8"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}