Gsontojson返回{}大括号

问题描述

请有人帮我解决问题。.我想将 BluetoothDevice 对象存储在SharedPrefrences中,以便下次打开应用程序时无需再次选择配对设备。我必须将此 BluetoothDevice 对象转换为 String 变量,然后将其存储到我使用过的SharedPrefrence中

Gson gson = new Gson();
String json = gson.toJson(selectedDevice,BluetoothDevice.class) ;

selectedDevice 是BluetoothDevice类的对象。但是运行代码后,我在json变量中得到了 {} 大括号。谁能知道为什么会这样。

解决方法

android.bluetooth.BluetoothDevice中的几乎所有属性均为static final。因此,这些属性不依赖于实例。

一个address属性可用,并且取决于实例变量。您可以使用address将此getAddress()属性保存到共享首选项中。

如果启用了蓝牙,您还可以使用getName()获取设备名称。

所以,我建议您在共享首选项中保存这样的内容;

class BluetoothDeviceInformation {

    String address;
    String name;

    @RequiresPermission(Manifest.permission.BLUETOOTH)
    public BluetoothDeviceInformation (
        BluetoothDevice device
    ) {
        this.address = device.getAddress();
        this.name = device.getName();
    }
}

您可以使用以下方法创建该实例:

BluetoothDeviceInformation deviceInformation = 
    new BluetoothDeviceInformation(selectedBluetoothDevice);

还有其他方法,例如getType()getAlias()等。如果需要他们的信息,只需将它们添加到BluetoothDeviceInformation类中即可。

,

假设您引用的是https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java,它包含静态字段,但是

Java序列化仅序列化对象的非静态和非瞬态字段

Doc

但是,如果您确实需要相同的方法,可以尝试:

BluetoothDevice selectedDevice = new BluetoothDevice();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
Gson gson = gsonBuilder.create();
String json = gson.toJson(selectedDevice,BluetoothDevice.class);