記錄一下 Gson的學習
1.添加依賴項
我是下載的 離線包
implementation files('libs/gson-2.2.4.jar')
2.設置bean
public class Child {
private int id;
private String name;
private String sex;
private int age;
private ArrayList<String> toys;
private HashMap<String, String> toysMap = new HashMap<String, String>();
private ArrayList<Book> books = new ArrayList<Book>();
public ArrayList<Book> getBooks() {
return books;
}
public void setBooks(ArrayList<Book> books) {
this.books = books;
}
public HashMap<String, String> getToysMap() {
return toysMap;
}
public void setToysMap(HashMap<String, String> toysMap) {
this.toysMap = toysMap;
}
public ArrayList<String> getToys() {
return toys;
}
public void setToys(ArrayList<String> toys) {
this.toys = toys;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
book 類
public class Book {
private String name;
private String price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
3.MainActivity 函數
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gson gson = new Gson();
Child child = new Child();
child.setId(1);
child.setAge(10);
child.setName("小孩A");
child.setSex("男");
ArrayList<String> toys = new ArrayList<String>();
toys.add("小車");
toys.add("皮卡丘");
toys.add("奧特曼");
toys.add("火影忍者");
child.setToys(toys);
HashMap<String, String> toysMap = new HashMap<String, String>();
toysMap.put("1", "小車2");
toysMap.put("2", "皮卡丘2");
toysMap.put("3", "奧特曼2");
toysMap.put("4", "火影忍者2");
child.setToysMap(toysMap);
ArrayList<Book> books = new ArrayList<Book>();
for (int i = 0; i < 3; i++) {
Book book = new Book();
book.setName("格林童話" + i);
book.setPrice("價格:" + i + "$");
books.add(book);
}
child.setBooks(books);
// Log.e("child", gson.toJson(child));
//將數據保存到 文件中,注意改文件是在手機上面
saveDataToFile("file.json",gson.toJson(child));
}
private void saveDataToFile(String fileName,String data){
FileOutputStream fileOutputStream = null;
BufferedWriter bufferedWriter = null;
try{
fileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
//getDir(fileName,Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(data);
}catch (Exception e){
e.printStackTrace();
}finally {
try
{
if (bufferedWriter != null)
{
bufferedWriter.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Gson的使用
1. Gson gson = new Gson();
2. 對象數據 mclass
3. 轉換成Gson: gson.toJson(mclass)
以上爲個人學習和理解,例子代碼已忘記來自哪個網站