Joffrey
11/27/2019, 2:48 PMkotlinx.serialization) in Kotlin/JS to parse JSON into Kotlin data classes?
@Test
fun jsonTest() {
data class Person(val name: String)
val expected = Person("Bob")
val parsedPerson = JSON.parse<Person>("""{"name":"Bob"}""")
assertEquals(expected, parsedPerson)
}
This test gives:
AssertionError: Expected <Person(name=Bob)>, actual <[object Object]>.diesieben07
11/27/2019, 2:50 PMRoman Artemev [JB]
11/27/2019, 2:51 PMJSON.parse constructs annonymous object with the similar layout. Could you please provide some details why kotlinx.serialization doesn’t fit your requirements?Joffrey
11/27/2019, 2:52 PMJoffrey
11/27/2019, 2:54 PMJoffrey
11/27/2019, 3:02 PMJSON.parse() to return T? If we can't ensure the instance returned will be of type T , shouldn't we just return some sort of JS object type?Roman Artemev [JB]
11/27/2019, 3:05 PMRoman Artemev [JB]
11/27/2019, 3:30 PMval o = js("{}")
o.__proto__ = js("Object.create(O.prtotype)")Roman Artemev [JB]
11/27/2019, 4:01 PMJoffrey
11/27/2019, 4:01 PMequals work in JS btw?Joffrey
11/27/2019, 4:02 PMT::class.members is not available in Kotlin/JS)Roman Artemev [JB]
11/27/2019, 4:02 PMequals? When you write == in kotlin?Joffrey
11/27/2019, 4:02 PMRoman Artemev [JB]
11/27/2019, 4:02 PMAny.equalsJoffrey
11/27/2019, 4:03 PMRoman Artemev [JB]
11/27/2019, 4:05 PMa == b becomes a.equals(b)Roman Artemev [JB]
11/27/2019, 4:06 PMequals usually checks for instanceofJoffrey
11/27/2019, 4:07 PMequals() on data classes checks for instanceof and this is based on JS prototype when compiled to JS? (I'm trying to understand how/why my sample code fails)Roman Artemev [JB]
11/27/2019, 4:08 PMRoman Artemev [JB]
11/27/2019, 4:10 PMdata class Dat(val start: String, val end: String)
equals in js going to be look like
Dat.prototype.equals = function (other) {
return this === other || (other !== null && (typeof other === 'object' && (Object.getPrototypeOf(this) === Object.getPrototypeOf(other) && (Kotlin.equals(this.start, other.start) && Kotlin.equals(this.end, other.end)))));
};Joffrey
11/27/2019, 4:11 PM== mapping to equals() work, how data classes generate equals(), and how equals() work in general in the JVM world and how Kotlin translates that to the JVM world. What I don't understand is what equals() does in the compiled JS code. Because I can access properties of the object returned by JSON.parse(), and they are equal to the ones of the expected instance, but equals() failsJoffrey
11/27/2019, 4:11 PMJoffrey
11/27/2019, 4:12 PMcopy() cannot be called on the object returned by JSON.parse(), but I only see the failure at runtimeRoman Artemev [JB]
11/27/2019, 4:13 PMJoffrey
11/27/2019, 4:14 PMRoman Artemev [JB]
11/27/2019, 4:16 PMJoffrey
11/27/2019, 4:16 PMkotlinx.serialization support to simplify the API if they're willing to use itRoman Artemev [JB]
11/27/2019, 4:17 PMDave
05/18/2021, 3:47 PM