# Unable to read properties from data object in Kotlin/JS

**URL:** <https://discuss.kotlinlang.org/t/unable-to-read-properties-from-data-object-in-kotlin-js/26897>\
**Category:** JavaScript\
**Created:** [June 5, 2023, 4:15pm UTC](https://discuss.kotlinlang.org/t/unable-to-read-properties-from-data-object-in-kotlin-js/26897 "2023-06-05T16:15:32Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![clovisai](https://avatars.discourse-cdn.com/v4/letter/c/a9adbd/32.png) [@clovisai](https://discuss.kotlinlang.org/u/clovisai)\
**Post date:** [June 6, 2023, 8:14am UTC](https://discuss.kotlinlang.org/t/unable-to-read-properties-from-data-object-in-kotlin-js/26897/2 "2023-06-06T08:14:53Z")

</div>

`JSON.parse` creates a new object with the fields it found. The created object:

- does _not_ belong to the original class
- does _not_ have any of the methods of the original class (e.g. no getters)
- does _not_ extend any of the interfaces or abstract classes its original class extends

This is a common problem in the JS world too: [Parsing JSON from Typescript restores data members but not type: cannot call methods on result - Stack Overflow](https://stackoverflow.com/a/17449450).

### Solution 1: manual hydration

```kotlin
// Let's imagine this is the class you want to put in the JSON
// You'll need to do this for *all* classes that become JSON
data class Point(val x: Int, val y: Int)

// To JSON
val json = JSON.stringify(Point(1, 2))

// From JSON
val deserialized = JSON.parse<Point>(json)
val result = Point(deserialized.x, deserialized.y) // force the creation of an instance of the class using the constructor

```

Note that if you go for this solution, you must call the constructor for _all_ objects in the JSON, recursively, even for things like `String`. `JSON.parse` only behaves as you expect for JS primitives (`Int` and smaller should be fine, `Float` and `Double` should be fine, `Boolean` should be fine—that’s it). Any object or class must be instantiated manually.

### Solution 2: don’t use JSON.parse

This problem is specific to JSON.stringify/JSON.parse. Another solution is to use something else, for example [KotlinX.Serialization](https://github.com/Kotlin/kotlinx.serialization).

```kotlin
@Serializable
data class Point(val x: Int, val y: Int)

// To JSON
val json = Json.encodeToString(Point(2, 3))

// From JSON
val result = Json.decodeFromString<Point>(json)

```

KotlinX.Serialization knows what class the object came from, and is able to recreate it exactly as you’d expect.

---

_[View the full topic](https://discuss.kotlinlang.org/t/unable-to-read-properties-from-data-object-in-kotlin-js/26897)._
