【问题标题】:Data binding failed数据绑定失败
【发布时间】:2019-08-13 04:19:08
【问题描述】:

我创建了一个新的芭蕾舞演员类型如下。

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

type INCIDENT_TYPE GENERAL|SECURITY;

public type incidentNotification record { 
    string title;
    INCIDENT_TYPE incidentType;

};

一旦我发送一个 POST 请求来创建一个新的事件通知,sendIncident 方法就会被执行。

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

与请求正文一起发送的 json 负载如下。

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

}

但是当我用http请求发送那个json时,它给出了错误

数据绑定失败:读取有效负载时出错:映射时出错 “incidentType”:不兼容的类型:预期 'janaka/incident-reporting-service:0.0.1:$anonType$4|janaka/incident-reporting-service:0.0.1:$anonType$5', 找到'字符串'

如何解决这个错误?

【问题讨论】:

  • 你能分享一些关于这个问题的背景吗?资源函数的示例代码将用作 HTTP 数据绑定功能,应该与资源函数一起使用。

标签: incompatibletypeerror ballerina


【解决方案1】:

这是 JSON 到 Record 转换中的一个错误,它已在 ballerina 最新版本中修复(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);
        }
    }
}

以上示例资源适用于以下请求

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

回复:

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

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 2013-02-05
    • 2014-10-19
    • 2019-08-26
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多