我正在实现一个简单的服务,其中输入
{ "a": <float>, "b": <float>, "operation": <string>}
现在,我想要两者
"a": 10
和
"a": 10.0
去工作。如果我只检查浮子案例,我会得到
error: error, message: 'int' cannot be cast to 'float'
我收到请求并执行以下操作
json operationReq = check req.getJsonPayload();
float a = 0;
var intInput = <int>operationReq.a;
match intInput {
int value => a = value;
error err => a = check <float>operationReq.a;
}
上面的代码有效。但这是正确的做法,还是黑客攻击?
我会为您的问题提出以下解决方案。您对j.a
的值执行类型切换。
import ballerina/io;
function main(string... args) {
json j = { "a": 10.0, "b": 4, "operation": "ddd"};
float a = 0;
var intInput = j.a;
match intInput {
int i => a = i;
float f => a = f;
json other => {} //error
}
}