ballerina - Ballerina 中 JSON int vs float 转换的最佳实践
问题描述
我正在实现一个带有输入的简单服务 where
{ "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
}
}
推荐阅读
- javascript - 数据未在本机反应中评估
- pandas - 使用熊猫数据框进行vlookup
- ios - 是否可以快速跟踪随机字符?
- python - 是否可以使用 PyCrypto 加密字节流?
- python - split(" ") 和 split() 有什么区别?
- ios - Swift - 过渡到 SceneDelegate
- javascript - WordPress 自定义插件开发中的纯 JavaScript 基本 AJAX 调用
- node.js - 这个错误对 nodejs 配置中的 MSAL 意味着什么?
- css - 选择父菜单
- powershell - 如何保持 io.filesystemwatcher 无限期运行