val json = Gson()
val jsonContent = json.toJson(sbn.notification.extras)

Gson解析的时候,用上述两行代码报如下错误:

nullcom.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 27 path $.mMap.android.title   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)   at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)   at com.google.gson.Gson.fromJson(Gson.java:887)   at com.google.gson.Gson.fromJson(Gson.java:852)   at com.google.gson.Gson.fromJson(Gson.java:801)   at com.google.gson.Gson.fromJson(Gson.java:773)   at tokyo.urbanlife.ulmapp.service.NLService.onNotificationPosted(NLService.kt:35)   at android.service.notification.NotificationListenerService.onNotificationPosted(NotificationListenerService.java:338)   at android.service.notification.NotificationListenerService$MyHandler.handleMessage(NotificationListenerService.java:1985)   at android.os.Handler.dispatchMessage(Handler.java:106)   at android.os.Looper.loop(Looper.java:280)   at android.app.ActivityThread.main(ActivityThread.java:6710)   at java.lang.reflect.Method.invoke(Native Method)   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 27 path $.mMap.android.title   at com.google.gson.stream.JsonReader.nextString(JsonReader.java:825)

后来toJson方法换了种写法:

 

 val jsonObject = JSONObject()
        val keys = sbn.notification.extras.keySet()
        for (key in keys) {
            try {
                jsonObject.put(key, JSONObject.wrap(sbn.notification.extras.get(key)))
            } catch (e: JSONException) {
                //Handle exception here
            }
        }
        val jsonContent = jsonObject.toString()

 

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐