Flutter 中的 Gson

Gson in Flutter

我正在使用 bluetooth.I 读取本机平台中的一些特征值然后将它们发送到 EventChannel 上的 Flutter

来开发 Flutter 应用程序
            DeviceInfo deviceInfo = new DeviceInfo(deviceData, value);
            Gson gson = new Gson();
            String json;
            json = gson.toJson(deviceInfo);
            Log.d("GetDeviceInformation", gson.toJson(deviceInfo));
            deviceInformation.success(json);

在调试测试期间,一切正常。当我构建应用程序的发布版本时,我得到的唯一结果是空地图 {}。 deviceInfo 变量很好。我唯一的线索是它可能与 Gson 和应用程序的发布版本有关。你有什么想法?

Marcono1234 的回答为我指明了正确的方向。 将以下代码添加到 app/build.gradle:

buildTypes {
    release {
        // TODO: Add your own signing config for the release build.
        // Signing with the debug keys for now, so `flutter run --release` works.
        signingConfig signingConfigs.debug

        minifyEnabled true
        useProguard true

        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

并遵循 app/proguard-rules.pro:

的混淆规则
-keep class com.example.** { *; }

#Flutter Wrapper
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.**  { *; }
-keep class io.flutter.util.**  { *; }
-keep class io.flutter.view.**  { *; }
-keep class io.flutter.**  { *; }
-keep class io.flutter.plugins.**  { *; }

##---------------Begin: proguard configuration for Gson  ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature

# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-dontwarn sun.misc.**
#-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { <fields>; }

# Prevent proguard from stripping interface information from TypeAdapter, TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * extends com.google.gson.TypeAdapter
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

# Prevent R8 from leaving Data object members always null
-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
}

# Retain generic signatures of TypeToken and its subclasses with R8 version 3.0 and higher.
-keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken
-keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken

##---------------End: proguard configuration for Gson  ----------