Search code examples
jsonballerina

Represent map of json and null in a record field


I need to define a record that can be used to represent the following values.

{
    "ID": "101",
    "name": "Dog",
    "types": null
}
{
    "ID": "101",
    "name": "Dog",
    "types": {
        "color": "black"
    }
}

The types field can be either JSON or null. The equivalent type is

type Animal record {
    string ID;
    string name;
    map<json> types?;
};

What is the best way of doing this?


Solution

  • If the value of the types field can be null, that requires the types record field to allow nil/null and that can be represented by map<json>?. An optional field map<json> types?; means the types field may or may not be present, but if present it will be a map<json> value. To allow nil/null the type has to allow nil.

    E.g.,

    • map<json>? types; - if the field is always present and the value can be map or nil
    • map<json>? types?; - if the field may or may not be present, and when present can be map or nil