簡體   English   中英

Gson().tojson() 返回 {} 大括號

[英]Gson().tojson() returning {} braces

請有人幫我找出問題..我想將BluetoothDevice對象存儲到SharedPrefences中,以便下次打開應用程序時無需再次選擇配對設備。為此,我必須將此BluetoothDevice對象轉換為String變量,然后將它存儲到我使用過的 SharedPrefence 中

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

其中selectedDevice是 BluetoothDevice 類的對象。 但是在運行代碼后,我在 json 變量中得到了{}大括號。 任何人都可以知道為什么會發生這種情況。

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類中即可。

假設您指的是https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java ,它包含靜態字段,但是,

Java 序列化僅序列化對象的非靜態和非瞬態字段

文件

但如果你真的需要它,你可以嘗試:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM