import ballerina/io;
// Closed type.
type ClosedCoord record {|
float x;
float y;
|};
// Open type, can have additional `anydata` fields.
type OpenCoord record {
float x;
float y;
};
public function main() {
ClosedCoord a = {x: 1.0, y: 2.0};
// Nothing to do.
json j = a;
io:println(j);
OpenCoord b = {x: 1.0, y: 2.0, "z": "city"};
// Use `toJson()` to convert `anydata` to `json`.
// Usually happens automatically.
json k = b.toJson();
io:println(k);
}
Converting from user-defined type to JSONConversion from |
import ballerina/io;
type ClosedCoord record {|
float x;
float y;
|};
Closed type.
type OpenCoord record {
float x;
float y;
};
Open type, can have additional anydata
fields.
public function main() {
ClosedCoord a = {x: 1.0, y: 2.0};
json j = a;
Nothing to do.
io:println(j);
OpenCoord b = {x: 1.0, y: 2.0, "z": "city"};
json k = b.toJson();
Use toJson()
to convert anydata
to json
.
Usually happens automatically.
io:println(k);
}
bal run converting_from_user_defined_type_to_json.bal
{"x":1.0,"y":2.0}
{"x":1.0,"y":2.0,"z":"city"}