Skip to content
This repository has been archived by the owner on Dec 3, 2020. It is now read-only.

Commit

Permalink
Correcting #20 & updating Gson to 2.8.0
Browse files Browse the repository at this point in the history
  • Loading branch information
SalomonBrys committed Jan 17, 2017
1 parent 3cfa04d commit 26bb3ca
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Expand Up @@ -50,7 +50,7 @@ repositories {
}

dependencies {
compile "com.google.code.gson:gson:2.7"
compile "com.google.code.gson:gson:2.8.0"

compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

Expand Down
16 changes: 15 additions & 1 deletion src/main/kotlin/com/github/salomonbrys/kotson/GsonBuilder.kt
Expand Up @@ -9,6 +9,7 @@ import java.lang.reflect.Type
import java.lang.reflect.WildcardType


@Suppress("PROTECTED_CALL_FROM_PUBLIC_INLINE")
inline fun <reified T: Any> gsonTypeToken(): Type = object : TypeToken<T>() {} .type

fun ParameterizedType.isWildcard() : Boolean {
Expand Down Expand Up @@ -42,14 +43,27 @@ fun ParameterizedType.isWildcard() : Boolean {
return hasAnyWildCard || (hasBaseWildCard && !hasSpecific)
}

fun removeTypeWildcards(type: Type): Type {

if (type is ParameterizedType) {
val arguments = type.actualTypeArguments
.map { if (it is WildcardType) it.upperBounds[0] else it }
.map { removeTypeWildcards(it) }
.toTypedArray()
return TypeToken.getParameterized(type.rawType, *arguments).type
}

return type
}

@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
inline fun <reified T: Any> typeToken(): Type {
val type = gsonTypeToken<T>()

if (type is ParameterizedType && type.isWildcard())
return type.rawType

return type
return removeTypeWildcards(type)
}


Expand Down
24 changes: 24 additions & 0 deletions src/test/kotlin/com/github/salomonbrys/kotson/TypeTokenSpecs.kt
@@ -1,5 +1,6 @@
package com.github.salomonbrys.kotson

import com.google.gson.Gson
import org.jetbrains.spek.api.Spek
import java.lang.reflect.ParameterizedType
import kotlin.test.assertEquals
Expand Down Expand Up @@ -201,6 +202,29 @@ class TypeTokenSpecs : Spek ({

}

given("a nested generic parameter type with wildcards") {

on("type-token-ization") {
it("should have removed the wildcards") {
val t = typeToken<List<List<Person>>>()
t as ParameterizedType
assertEquals(List::class.java, t.rawType)
val p1 = t.actualTypeArguments[0]
p1 as ParameterizedType
assertEquals(List::class.java, p1.rawType)
val p2 = p1.actualTypeArguments[0]
assertEquals(Person::class.java, p2)
}
}

on("deserialization") {
it("should have understood the generic type") {
assertEquals("Salomon", Gson().fromJson<List<List<Person>>>("[ [ { name: \"Salomon\", age: 30 } ] ]")[0][0].name)
}
}

}

}) {

interface Base
Expand Down

0 comments on commit 26bb3ca

Please sign in to comment.