繁体   English   中英

如何在 Android Studio (Java) 中序列化一个还包含两个 ArrayList 对象的对象?

[英]How do I serialize an object that also contains two ArrayList of objects in Android Studio (Java)?

总的来说,我对 Android Studio 和 Java 都很陌生。 我想序列化一个包含 2 个对象 ArrayList 的对象,我已经看到有几种方法可以实现这一点,比如 SharedPreferences 但我现在有点迷失了。

我要序列化的类是这样的:

public class User implements Serializable {
public String userName="";
public float currentBalance=0;
public float totalExpenses=0;
public float totalIncome=0;
public float ocassionalExpenses=0;
public float ocassionalIncome=0;
public float monthlyExpenses=0;
public float monthlyIncome=0;
public ArrayList<Expense> expenses;
public ArrayList<Income> income;

public User(){
    this.expenses=new ArrayList<Expense>();
    this.income =new ArrayList<Income>();


}

收入和费用两个类看起来像这样

public class Expense implements Parcelable, Serializable {

public String name;
public boolean recurring;
public float prize;



public Expense(String name, boolean recurring, float prize){
    this.name=name;
    this.recurring=recurring;
    this.prize=prize;
}

public class Income implements Parcelable, Serializable {
public String name;
public boolean recurring;
public float prize;

public Income(String name, boolean recurring, float prize){
    this.name=name;
    this.recurring=recurring;
    this.prize=prize;
}

每当我对任一对象进行任何更改时,我都想用两个 ArrayLists 的信息序列化用户类,并在打开应用程序时读取此信息。 我应该如何解决这个问题?

好的,据我了解。 将帮助您了解 GSON 解串器库。

首先添加对build.gradle的依赖:

dependencies {
  implementation 'com.google.code.gson:gson:2.9.0'
}

然后在您的主类或按钮的单击事件上测试它,例如:

User user = new User(1 L, "halil", "sahin",
    LocalDate.of(1991, Month.JANUARY, 1), new Department(2, "Software Engineering", true));

Gson gson = new GsonBuilder()
    .setPrettyPrinting()
    .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
    .create();

String jsonString = gson.toJson(user);

Toast.makeText(getApplicationContext, "Result :" + jsonString, Toast.LENGTH_LONG).show();

用户类就是一个例子。 你可以适应你的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM