Back to Examples

Casting JSON to user-defined type

In order to access the field in the json value, the easiest way is to convert the json value to a user-defined type.

The type-casting can be used to do that. However, if the cast fails, the program panics with an error. The recommended way to do this is by using langlib functions.

Casting to a user-defined type will work on mutable structure only if the inherent type (a structured value has an inherent type, which is a type descriptor that is part of the structured value's runtime value) of that structure is a subtype of the user-defined type.

Casting immutable values will work. However, 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};
    
    // Here, the inherent type of `j` is not a subtype of `Coord`. 
    // Therefore, `j` cannot be directly converted to `Coord`.
    // Use `cloneReadOnly()` to create a read-only copy of the mutable value `j`.
    // Then, the resulting immutable value can be casted successfully.
    json k = j.cloneReadOnly();
    Coord c = <Coord> k;
    
    io:println(c.x);
    io:println(c.y);
}
$ bal run casting_json_to_user_defined_type.bal1.02.0

Related links

PreviousConvert from JSON to user-defined type
NextResource method typing