import ballerina/io;

type Coord record {
    float x;
    float y;
};

public function main() {
    json j = {x: 1.0, y: 2.0};
    
    
    // With mutable values, it would not be type-safe to allow a cast.
    // Cast to `T` will work on the mutable structure `s` only if the inherent type
    // of `s` is a subtype of `T`.
    // Use `cloneReadOnly()` to create a read-only copy of the mutable value.
    // Then, you can cast the resulting immutable value successfully.
    json k = j.cloneReadOnly();
    Coord c = <Coord> k;

    io:println(c.x);
    io:println(c.y);
}

Converting from JSON to user-defined type

With mutable values, it would not be type-safe to allow a cast. Mutable structures have the inherent type that limits mutation. Cast to T will work on mutable structure s only if the inherent type of s is a subtype of T. Casting immutable values will work but it does not do numeric conversions.

import ballerina/io;
type Coord record {
    float x;
    float y;
};
public function main() {
    json j = {x: 1.0, y: 2.0};
    
    
    json k = j.cloneReadOnly();
    Coord c = <Coord> k;

With mutable values, it would not be type-safe to allow a cast. Cast to T will work on the mutable structure s only if the inherent type of s is a subtype of T. Use cloneReadOnly() to create a read-only copy of the mutable value. Then, you can cast the resulting immutable value successfully.

    io:println(c.x);
    io:println(c.y);
}
bal run converting_from_json_to_user_defined_type.bal
1.0
2.0