有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Gson()。tojson()返回{}大括号

请有人帮我解决这个问题。。我想将蓝牙设备对象存储到SharedPreferences中,以便下次打开应用程序时无需再次选择配对设备。为此,我必须将这个BluetoothDevice对象转换为字符串变量,然后将其存储到我使用的SharedPreference中

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

其中,selectedDevice是Bluetooth设备类的对象。但是在运行代码之后,我得到了json变量中的大括号。有谁知道为什么会这样吗


共 (2) 个答案

  1. # 1 楼答案

    假设您引用的是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);
    
  2. # 2 楼答案

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

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

    如果启用了蓝牙,还可以通过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类中即可