ballerina-platform / ballerina-library

The Ballerina Library
https://ballerina.io/learn/api-docs/ballerina/
Apache License 2.0
136 stars 64 forks source link

NPE when Converting Record to XML Using 'xmldata:toXml()' #6619

Open DimuthuMadushan opened 5 months ago

DimuthuMadushan commented 5 months ago

Description: Consider the following code:

import ballerina/xmldata;
import ballerina/io;

type Response record {|
    string? status;
    int? value;
    boolean? isTrue;
|};

public function main() returns error? {
    Response response = {
        status: "success",
        value: 10,
        isTrue: ()
    };
    xml x = check xmldata:toXml(response);
    io:println(x);
}

When there is a () value in the record, this returns a NPE.

error: java.lang.NullPointerException {"message":"Cannot invoke "Object.getClass()" because "value" is null"}
        at ballerina.xmldata.2:getModifiedRecord(xmldata.bal:96)
           ballerina.xmldata.2:toXml(xmldata.bal:68)
           xmldata:main(xmldata.bal:16)

Bal version: 2201.8.6

daneshk commented 5 months ago

We are not supporting nullable fields. We only support optional fields like below,

import ballerina/xmldata;
import ballerina/io;

type Response record {|
    string status?;
    int value?;
    boolean isTrue?;
|};

public function main() returns error? {
    Response response = {
        status: "success",
        value: 10,
        isTrue: ()
    };
    xml x = check xmldata:toXml(response);
    io:println(x);
}

This will remove the element completely when the value is nil or not set.

daneshk commented 5 months ago

Referring to the SFO[1], we should support nillable fields by adding the attribute xsi:nil="true" to the nil fields

  1. https://stackoverflow.com/questions/774192/what-is-the-correct-way-to-represent-null-xml-elements