Convert Java object to a Ballerina JSON value

68 Views Asked by At

Is it possible to convert Java objects into Ballerina objects and/or JSON types? I want to use the POI Java package to read XLSX and make it available in Ballerina land as a record[] or json[] or something else.

1

There are 1 best solutions below

0
Ayesh Almeida On

Yes, you can achieve this using Java interoperability and the bindgen tool to generate Ballerina objects corresponding to Java objects. Check out the following resources for more information:

However, note that there is no direct way to convert Java objects to Ballerina records or JSON types. Here are a couple of options:

  1. If you have a string representation in JSON format, you can use the fromJsonStringWithType function to convert it to an array of JSON or records.

    import ballerina/jballerina.java;
    
    type Employee record {|
        int id;
        string name;
        json...;
    |};
    
    // `jsonJavaStr` is the Java String that is in JSON format.
    function convertToEmployees(handle jsonJavaStr) returns Employee[]|error {
        string? jsonBalStr = java:toString(jsonJavaStr);
    
        if jsonBalStr is () {
            return error("expected non-empty string");
        }
    
        return jsonBalStr.fromJsonStringWithType();
    }
    
  2. You could create the Java representation of json[] in an external function you implement (actual conversion would happen in Java). For example, creating a io.ballerina.runtime.api.values.BArray value using io.ballerina.runtime.api.creators.ValueCreator#createArrayValue.

    // `javaObj` is the reference to the Java object.
    function constructJsonArray(handle javaObj) returns json[] = external;
    

    This approach involves more work since you'll have to create a new array type and recursively parse/map the values too.