import ballerina/io;
type person {
    string fname;
    string lname;
    int age;
};type movie{
    string title;
    string year;
    string released;
    person writer;
};
function main (string[] args) {
    movie theRevenant = {title:"The Revenant", year:"2015",
                            released:"08 Jan 2016",
                            writer:{fname:"Michael",
                                       lname:"Punke", age:30}};
    json j = check <json>theRevenant;
    io:println(j);
    io:println(j.writer.lname);
    map m = <map>theRevenant;
    person writer = check <person>m["writer"];
    io:println(writer.age);
    json inceptionJ = {title:"Inception", year:"2010",
                          released:"16 Jul 2010",
                          writer:{fname:"Christopher",
                                     lname:"Nolan", age:30}};
    movie inception = check <movie>inceptionJ;
    io:println(inceptionJ);
}

JSON/Struct/Map Conversion

Ballerina structs, maps, and JSON objects are used to hold records. Records are collections of fields, and each field value is accessed by a key. Converting from one type to another is very useful in certain situations.

import ballerina/io;
type person {
    string fname;
    string lname;
    int age;
};

This is a Ballerina struct.

type movie{
    string title;
    string year;
    string released;
    person writer;
};
function main (string[] args) {
    movie theRevenant = {title:"The Revenant", year:"2015",
                            released:"08 Jan 2016",
                            writer:{fname:"Michael",
                                       lname:"Punke", age:30}};

This function creates a movie object.

    json j = check <json>theRevenant;
    io:println(j);
    io:println(j.writer.lname);

Here’s how you can convert a struct to a JSON object. This conversion is unsafe because it may not be possible to convert some data types that are defined in the struct, to JSON.

    map m = <map>theRevenant;
    person writer = check <person>m["writer"];
    io:println(writer.age);

Similarly, you can convert a struct to a map. This conversion is safe.

    json inceptionJ = {title:"Inception", year:"2010",
                          released:"16 Jul 2010",
                          writer:{fname:"Christopher",
                                     lname:"Nolan", age:30}};
    movie inception = check <movie>inceptionJ;
    io:println(inceptionJ);
}

Here’s how you can convert a JSON object to a struct. This conversion is unsafe because the field names and types are unknown until runtime.

$ ballerina run json-struct-map-conversion.bal
{"title":"The Revenant","year":"2015","released":"08 Jan 2016",
    "writer":{"fname":"Michael","lname":"Punke","age":30}}
Punke
30
{"title":"Inception","year":"2010","released":"16 Jul 2010",
    "writer":{"fname":"Christopher","lname":"Nolan","age":30}}

At the command line, navigate to the directory that contains the .bal file and run the ballerina run command.