Kotlin application Gson

introduction


Is Gson very simple and easy to use? The most important are the two methods toJson() and fromJson() to convert entities to Json and convert Json to entities.

I haven't used Gson before, let alone Kotlin. Since the use time is not very long, it is really hard to say whether it is good or not.

I used to use Json before and with the help of this JsonHelper tool class , I temporarily think that JsonHelper is not as easy to use and its functions are not as practical as JsonHelper.

Mainly because of the pits that will be described below.

text


In the process of writing a project, I need to save some temporary data, and naturally I thought of the SpUtils class created before to store the data in SharedPreferences.

So I wrote two methods to perfectly meet the requirements

        fun <T> getObject(key: String, cls: Class<T>): T {
            var value = getString(key, "")
            return gson.fromJson<T>(value, cls)
        }

        fun setObject(key: String, obj: Any) {
            var value = gson.toJson(obj)
            setString(key, value)
        }

The main idea is to convert the entity into a Json string to save, take out the Json string when needed, and serialize it into an entity for return.

At this time, the demand has been upgraded, and a list needs to be saved.

        fun <T> getList(key: String, cls: Class<T>): List<T> {
            var value = getString(key, "")
            if (TextUtils.isEmpty(value)) {
                return ArrayList()
            }
            return gson.fromJson(value, object : TypeToken<List<T>>() {}.type)
        }

At this time, it seems that there is nothing wrong, the program can be compiled normally, but it crashes when it runs to fetch the variable of the entity

error

Type conversion failed? ? why? ? go through debug

stored data

Stored Json

retrieved data

The problem arises. The objects contained in the original List have been stored and retrieved, but the List has become a key-value pair.

It can be concluded that Gson is not serialized successfully.

After spending a lot of thought and searching for a lot of information, I finally understood. The reason is type erasure in java

Generics in Java are basically implemented at the compiler level. Type information in generics is not included in the generated Java bytecode. Type parameters added when using generics will be removed when the compiler compiles. This process is called type erasure.
https://segmentfault.com/q/1010000009644038

Since I used generics, fromJson() only knows that it is a List but the type inside is unknown, so it returns a key-value pair.

Therefore, the method of passing the type is adopted here, otherwise the serialization will fail because the type cannot be found.

        fun <T> getList(key: String, type: Type): T {
            var value = getString(key, "")
            return gson.fromJson(value, type)
        }
SpUtils.getList<List<Category>>(KEY_CATEGORY_LIST, object : TypeToken<List<Category>>() {}.type)

From this point of view, the previous JsonHelper will not have this problem.

I can't kill it with one stick, I still continue to go deeper with the attitude of learning.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325995137&siteId=291194637