本文介绍了如何在Android中保存自定义Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能帮帮我吗?我正在尝试将我的Java Objects(Customer)保存在android中,目前我正在学习一本书.

Can you help me out. I am trying to save my Java Objects(Customer) in android currently I am following a book in my studies.

这就是我得到的,我有具有字符串和UUID的客户对象.通过这些,我可以通过使用JSON转换将其成功保存.我的问题是我想为每个客户添加一个对象的ArrayList,其中包含(双精度和两个字符串).将客户对象转换为json时,如何保存此ArrayList并在该JSON对象中检索它.

This is what I got, I have Customer Object that has a String and UUID. With these I am able to save them successfully through converting it with JSON. My problem is I want to add an ArrayList of Objects which contains(Double, and two strings) for each Customer. How can I save this ArrayList and retrieve it inside that JSON Object when I convert my Customer Object to json.

我进行了研究,但并不能很好地理解它.我找到了GSON,但是我不确定这是否是我需要的那个,并且不知道如何将这个库添加到我的项目中.另一个是我可以将JSONArray放入JSON对象吗?这是我发现但不确定的两个潜在解决方案.我正在尝试通过文件而不是SQLite保存该文件.反正有吗?

I researched but can't really understand it well. I found GSON but I am not sure whether this is the one I needed and don't know how to add this library to my project. Another is can I be able to put JSONArray into a JSON object? These are the two potential solutions that I found but not that sure. I'm trying to save this through file not SQLite. Is there anyway?

这是Customer类的代码

Here is the code for the Customer class

    public class Customer {

//Constants for JSON
private static final String JSON_ID = "id";
private static final String JSON_NAME = "name";

private String mName;
private UUID mID;
private ArrayList<Item> mItems;

public Customer(){
    mID = UUID.randomUUID();
    mItems = new ArrayList<Item>();
}

//Loading Customer from JSON
public Customer(JSONObject jsonObject) throws JSONException{
    mID = UUID.fromString(jsonObject.getString(JSON_ID));
    if(jsonObject.has(JSON_NAME)){
        mName = jsonObject.getString(JSON_NAME);
    }
}


//JSON converter
public JSONObject toJSON() throws JSONException{
    JSONObject json = new JSONObject();
    json.put(JSON_ID, mID.toString());
    json.put(JSON_NAME,mName);
    if (!mItems.isEmpty()){

    }
    return json;
}


public UUID getmID() {
    return mID;
}

public String getmName() {
    return mName;
}

public void setmName(String mName) {
    this.mName = mName;
}

//Add item debt
public void addDebt(Item i){
    mItems.add(i);
}

//Get List Debt
public ArrayList<Item> getmItems(){
    return mItems;
}

public Item getItem(UUID id){
    for (Item item : mItems){
        if (item.getmItemID().equals(id)){
            return item;
        }
    }
    return null;
}

}

这是用于物品

   public class Item {

private String mItemName;
private Date mDate;
private UUID mItemID;
private double mPrice;


public Item(){
    mDate = new Date();
    mItemID = UUID.randomUUID();
}

public UUID getmItemID() {
    return mItemID;
}

public void setmItemID(UUID mItemID) {
    this.mItemID = mItemID;
}

public String getmItemName() {
    return mItemName;
}

public void setmItemName(String mItemName) {
    this.mItemName = mItemName;
}

public String toString(){
    return mItemName;
}

public Date getmDate() {
    return mDate;
}

public void setmDate(Date mDate) {
    this.mDate = mDate;
}

public double getmPrice() {
    return mPrice;
}

public void setmPrice(double mPrice) {
    this.mPrice = mPrice;
}

}

推荐答案

您可以执行以下操作将包括ArrayList在内的整个对象转换为json,然后可以将其保存到您的SharedPreferences

You could do the following to convert your entire object including the ArrayList into json and you can then save this into your SharedPreferences

为此,您需要导入GSON库.这是您的操作方式.

To do this you need to import the GSON library. Here's how you do that.

如果您使用的是Android Studio

if you're using Android Studio

  • 转到您的build.gradle文件并打开它
  • 向下滚动直到看到dependencies
  • 添加以下行并同步项目(选项将出现在屏幕顶部compile 'com.google.code.gson:gson:2.3.1'
  • Go to your build.gradle file and open it
  • Scroll down until you see dependencies
  • add the following line and synchronize the project(option will apear on top of the screen compile 'com.google.code.gson:gson:2.3.1'

如果您使用的是Eclipse

if you're using Eclipse

  • 下载 gson罐
  • 右键单击您的项目,然后选择属性
  • 选择左侧的"Java构建路径",然后选择库"选项卡.现在,单击添加外部JARS ..."按钮
  • 找到并选择您刚刚下载的jar文件,然后单击打开"
  • 最后单击确定",您应该可以在引用的库下看到它
  • Download the gson jar
  • Right click your project and select properties
  • Select "Java Build Path" on the left, and then the "Libraries" tab. Now, click the "Add External JARS..." button
  • Locate and select the jar file you just downloaded, and then click "Open"
  • Finally click "ok" and you should be able to see it under referenced libraries

现在输入代码,看起来像这样

Now for the code it would look something like this

SharedPreferences mSettings = getSharedPreferences("YourPreferenceName", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSettings.edit();

GsonBuilder gsonb = new GsonBuilder();
Gson mGson = gsonb.create();

假设您有2种方法,一种用于保存对象,另一种用于读取对象.

let's say you have 2 methods one for saving your object and one for reading it.

public boolean writeJSON(Customer c, String yourSettingName)
{
   try {
       String writeValue = mGson.toJson(c);
       mEditor.putString(yourSettingName, writeValue);
       mEditor.commit();
       return true;
   }
   catch(Exception e)
   {
       return false;
   }
}

public Customer readJSON(String yourSettingName)
{
   String loadValue = mSettings.getString(yourSettingName, "");
   Customer c = mGson.fromJson(loadValue, Customer.class);
   return c;
}

然后,您可以只调用这些方法,它会告诉您写入是否成功,当您调用读取时,它将返回您之前保存的客户对象.

You then can just call those methods and it will let you know if the writing was successfull and when you call the read it'll return your customer object you saved previously.

希望这可以帮助您

这篇关于如何在Android中保存自定义Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 23:13
查看更多