GSON is a JSON parsing library provided by Google. You can convert Java objects and JSON, but Kotlin can. This time, I could easily convert it with Kotlin's MutableMap, so I would like to share it.
Write the following in Android Studio.
build.gradle
dependencies {
implementation 'com.google.code.gson:gson:*.*.*'
}
"*. *. *" Describe the latest version. Check the latest version from the following. https://github.com/google/gson
After writing the above, click "Sync Now" on Android Studio and you're ready to go.
GSON is now available in your project.
I implemented the JSON conversion process as follows.
Sample.java
public void test(){
ArrayMap<String, String> map = new ArrayMap<>();
map.put("a1", "A1");
map.put("a2", "A2");
map.put("a3", "A3");
Gson gson = new Gson();
String jsonString = gson.toJson(map);
Log.d("Java", jsonString);
Type type = new TypeToken<ArrayMap<String, String>>(){}.getType();
ArrayMap<String, String> map2 = gson.fromJson(jsonString, type);
for (String mapValue : map2.values()) {
Log.d("Java", mapValue);
}
}
When you check the log
D/Java: {"a1":"A1","a2":"A2","a3":"A3"} D/Java: A1 A2 A3
become that way. It was confirmed that JSON conversion is possible. Up to this point, it's been done before, so there's nothing new.
The main subject is from here. Implement the above Java implementation in Kotlin. Map uses Kotlin's MutableMap.
Sample.kt
fun test(){
val map : MutableMap<String, String> = mutableMapOf()
map.put("a1", "A1")
map.put("a2", "A2")
map.put("a3", "A3")
val gson = Gson()
val jsonString : String = gson.toJson(map)
Log.d("Kotlin", jsonString)
val type : Type = object : TypeToken<MutableMap<String, String>>() {}.type
val map2 : MutableMap<String, String> = gson.fromJson(jsonString, type)
for (mapValue in map2.values) {
Log.d("Kotlin", mapValue)
}
}
When you check the log
D/Kotlin: {"a1":"A1","a2":"A2","a3":"A3"} D/Kotlin: A1 A2 A3
become that way. It was confirmed that JSON conversion can be performed in the same way as Java.
The ease of use of Kotlin is GOOD!
Recommended Posts