首页 > 解决方案 > 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;
}

上面的代码有效。但这是正确的做法,还是黑客行为?

标签: ballerina

解决方案


对于您的问题,我会建议以下解决方案。您对 的值进行类型切换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
    }
}

推荐阅读