Janaka
Janaka

Reputation: 471

Data binding failed

I created a new Ballerina type as below.

const string GENERAL="GENERAL";
const string SECURITY="SECURITY";

type INCIDENT_TYPE GENERAL|SECURITY;

public type incidentNotification record { 
    string title;
    INCIDENT_TYPE incidentType;

};

Once I send a POST request to create a new incidentNotification, sendIncident method is executed.

public function sendIncident (http:Request req, incidentNotification sendIncidentBody) returns http:Response {}

The json payload that is sent with the request body as follows.

{
    "title":"title",
    "incidentType": "SECURITY"

}

But when I send that json with http request, it gives the error

data binding failed: Error in reading payload : error while mapping 'incidentType': incompatible types: expected 'janaka/incident-reporting-service:0.0.1:$anonType$4|janaka/incident-reporting-service:0.0.1:$anonType$5', found 'string'

How to solve this error?

Upvotes: 0

Views: 336

Answers (1)

Chamil E
Chamil E

Reputation: 478

It's a bug in the JSON to Record conversion and it is fixed in the ballerina latest release(v1.0.0-alpha)

import ballerina/http;
import ballerina/log;

const string GENERAL="GENERAL";
const string SECURITY="SECURITY";

type INCIDENT_TYPE GENERAL|SECURITY;

public type IncidentNotification record { 
    string title;
    INCIDENT_TYPE incidentType;
};

service hello on new http:Listener(9090) {
    @http:ResourceConfig {
        methods: ["POST"],
        body: "notification"
    }
    resource function bindJson(http:Caller caller, http:Request req, 
                                      IncidentNotification notification) {
        var result = caller->respond(notification.title);
        if (result is error) {
           log:printError(result.reason(), err = result);
        }
    }
}

Above sample resource works fine for following request

curl -v http://localhost:9090/hello/bindJson -d '{ "title": "title" , "incidentType" : "SECURITY"}' -H "Content-Type:application/json"

Response:

< HTTP/1.1 200 OK
< content-type: text/plain
< content-length: 5
< 
* Connection #0 to host localhost left intact
title

Upvotes: 0

Related Questions