1 package kotlinx.serialization.json 2 3 import com.google.gson.* 4 import kotlinx.serialization.* 5 import org.junit.Test 6 import kotlin.test.* 7 8 class GsonCompatibilityTest { 9 10 @Serializable 11 data class Box(val d: Double, val f: Float) 12 13 @Test testNaNnull14 fun testNaN() { 15 checkCompatibility(Box(Double.NaN, 1.0f)) 16 checkCompatibility(Box(1.0, Float.NaN)) 17 checkCompatibility(Box(Double.NaN, Float.NaN)) 18 } 19 20 @Test testInfinitynull21 fun testInfinity() { 22 checkCompatibility(Box(Double.POSITIVE_INFINITY, 1.0f)) 23 checkCompatibility(Box(1.0, Float.POSITIVE_INFINITY)) 24 checkCompatibility(Box(Double.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)) 25 } 26 27 @Test testNumbernull28 fun testNumber() { 29 checkCompatibility(Box(23.9, 23.9f)) 30 } 31 checkCompatibilitynull32 private fun checkCompatibility(box: Box) { 33 checkCompatibility(box, Gson(), Json) 34 checkCompatibility(box, GsonBuilder().serializeSpecialFloatingPointValues().create(), Json { allowSpecialFloatingPointValues = true }) 35 } 36 checkCompatibilitynull37 private fun checkCompatibility(box: Box, gson: Gson, json: Json) { 38 val jsonResult = resultOrNull { json.encodeToString(box) } 39 val gsonResult = resultOrNull { gson.toJson(box) } 40 assertEquals(gsonResult, jsonResult) 41 42 if (jsonResult != null && gsonResult != null) { 43 val jsonDeserialized: Box = json.decodeFromString(jsonResult) 44 val gsonDeserialized: Box = gson.fromJson(gsonResult, Box::class.java) 45 assertEquals(gsonDeserialized, jsonDeserialized) 46 } 47 } 48 resultOrNullnull49 private fun resultOrNull(function: () -> String): String? { 50 return try { 51 function() 52 } catch (t: Throwable) { 53 null 54 } 55 } 56 } 57