如何使用gson在android中使用自定义对象属性序列化类?

时间:2016-02-10 18:41:29

标签: java android object sharedpreferences gson

我想使用Gson库来序列化和存储一个名为“Battery”的自定义类的对象。在Battery类中,我定义了另一个自定义对象的数组,即“Cannon”。这是我的两个班级:

Cannon.java:

import android.widget.ImageView;

public class Cannon {
    private String id; // used for object storage
    private int number; // Cannon number in battery
    private ImageView icon;

    private long utmEast, utmNorth; // Used to define cannon global location
    private boolean isBase; // Defines if the cannon is base

    private double flyingTime;
    private int angle, side;

    public Cannon() {

    }

    public Cannon(String id, int number, ImageView icon, String connectionNumber){
        this.id = id;
        this.number = number;
        this.icon = icon;
        this.connectionNumber = connectionNumber;
    }

    public String getId() {
        return this.id;
    }

    public int getNumber() {
        return this.number;
    }

    public ImageView getIcon() {
        return this.icon;
    }

    public long getUtmNorth() {
        return utmNorth;
    }

    public void setUtmNorth(long utmNorth) {
        this.utmNorth = utmNorth;
    }

    public long getUtmEast() {
        return utmEast;
    }

    public void setUtmEast(long utmEast) {
        this.utmEast = utmEast;
    }

    public void setAsBase(boolean isBase) {
        this.isBase = isBase;
    }

    public boolean isBaseCannon() {
        return isBase;
    }
}

Battery.java:

public class Battery {

    private String id; // used for object storage

    private final Cannon cannons[] = new Cannon[6];

    public Battery(String id){
        this.id = id;
    }

    public String getId() {
        return this.id;
    }

    public Cannon[] getCannons() {
        return cannons;
    }

    public void setCannon(Cannon cannon, int position) {
        this.getCannons()[position] = cannon;
    }

    public Cannon getCannon(String cannonId) {
        for (Cannon cn: this.getCannons()) {
            if (cn.getId() == cannonId) {
                return cn;
            }
        }
        return null;
    }

    public Cannon getCannon(int position) {
        return getCannons()[position];
    }
}

这是我的Preferences类,它使用共享首选项来存储特定于应用程序的字段,包括使用Gson库的电池对象。

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import net.adeveloper.firecontrol.data.Battery;

/** stores the user object in SharedPreferences */
public class Preferences {
    /** This application's preferences label */
    private static final String PREFS_NAME = "net.adeveloper.firecontrol.preferences";
    /** This application's preferences */
    private static SharedPreferences settings;
    /** This application's settings editor*/
    private static SharedPreferences.Editor editor;
    /** Constructor takes an android.content.Context argument*/
    private final Gson gson = new Gson();

    /**************************************************/

    private final Battery battery = new Battery(Reference.BATTERY_ID);

    /**************************************************/

    public Preferences(Context ctx){
        if(settings == null){
            settings = ctx.getSharedPreferences(PREFS_NAME,
                    Context.MODE_PRIVATE );
        }
       /*
        * Get a SharedPreferences editor instance.
        * SharedPreferences ensures that updates are atomic
        * and non-concurrent
        */
        editor = settings.edit();

        // Initialize battery
        String battery_json = gson.toJson(battery);
        // store in SharedPreferences
        String id = battery.getId(); // get storage key
        editor.putString(id, battery_json);
        editor.commit();
    }

    public Battery getBattery() {
        String battery_json = settings.getString(Reference.BATTERY_ID, "");
        Battery battery = gson.fromJson(battery_json, Battery.class);
        return battery;
    }

    //...

}

我使用MainActivity中的首选项对象来存储应用程序字段:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //...

        /********************************************************/

        prefs = new Preferences(this.getApplicationContext());

        /********************************************************/

然而,当它启动时,应用程序崩溃并输出Gson stackoverflowError:

02-10 16:39:03.110 13187-13187/net.adeveloper.firecontrol E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            java.lang.StackOverflowError
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
                                                                                at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:355)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:117)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
                                                                                at com.google.gson.Gson.getAdapter(Gson.java:356)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:82)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:81)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:118)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
                                                                                at com.google.gson.Gson.getAdapter(Gson.java:356)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:82)
                                                                                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.cr

更新

我在setContentView之后将此代码添加到我的MainActivity,因为我使用的是Android版本为4.2.1的设备:

@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

//...

                /********************************************************/

                prefs = new Preferences(this.getApplicationContext());

                /********************************************************/

现在stackoverflow异常已经消失了,但现在又出现了另一个问题,即由toJson()和fromJson()方法返回的我的Json字符串为null,当我通过电池类设置我的cannon对象时,使用Preference对象实际上无法访问它再次返回null:

Cannon cannon = new Cannon(id, number, icon, phone);
                prefs.getBattery().setCannon(cannon, position);
                if (prefs.getBattery().getCannons() == null) {
                    Log.d("Cannon", "NULL");
                } else {
                    for (Cannon cn: prefs.getBattery().getCannons()) {
                        Log.d("Cannon", cn + "");
                    }
                }

输出:

Cannon: null
Cannon: null
Cannon: null
Cannon: null
Cannon: null
Cannon: null

1 个答案:

答案 0 :(得分:1)

我没有得到你想要达到的目标?但你可以  1.将objec转换为json
 2.保存在SharedPreference中然后再生  3.再次可以从偏好中选择json  4.并转换为java Object

示例

class Test
  {
     int id = 1;
     int name = "testing";
     }

class Main{
 Test t = new Test;
 String s = ConvertToJson(t);

 /* save the string in SharedPreferecne and you can get any 
   time string and convert again for eg.*/

  Test t2 =  ConvertToTest(TestJsonSring);

  public Test ConvertToTest(String json) {
    return new Gson().fromJson(json, Test.class);
    }

   public String ConvertToJson(Object object) {
    Gson gson = new Gson();
    return gson.toJson(object);
   }
  }