我得到一个异常,感觉它可能是一个缺陷。我想知道是否有其他人看到这个问题。这是我正在编写的简化但可运行的服务。
import ballerina.net.http;
import ballerina.lang.messages;
import ballerina.lang.jsons;
import ballerina.lang.system;
@http:BasePath("/weather")
service WeatherService {
@http:GET
@http:Path("/current")
resource current(message m) {
string url = "http://api.mesowest.net/v2/stations/nearesttime?stid=KBFI&within=60&vars=air_temp,wind_speed,wind_direction&obtimezone=local&token=demotoken";
http:ClientConnector weatherConnector = create http:ClientConnector(url);
message request = {};
message jsonResponse = http:ClientConnector.get(weatherConnector, "", request);
json jsonDocument = messages:getJsonPayload(jsonResponse);
json timestamp;
string timeString;
try {
timestamp = jsons:getJson(jsonDocument, "$..PERIOD_OF_RECORD.end");
}
catch (exception e) {
system:println("Error getting timestamp");
}
messages:setJsonPayload(m, timestamp);
reply m;
}
}
当我在调试器中运行它时,json变量' timestamp'从下面的JSON摘录中分配了适当的值:
"STATION": [
{
"STATUS": "ACTIVE",
"MNET_ID": "1",
"PERIOD_OF_RECORD": {
"start": "1969-12-31T16:00:00-0800",
"end": "2017-02-27T19:40:00-0800"
}
当我更换线路时:
timestamp = jsons:getJson(jsonDocument, "$..PERIOD_OF_RECORD.end");
行
timeString = jsons:getString(jsonDocument, "$..PERIOD_OF_RECORD.end");
并停止并重新启动服务并对其进行测试,它会在getString方法上抛出异常。我还没有找到一种方法来打印异常,或者获取异常的属性以找出失败的原因。控制台输出如下。
Running weather2.bal service.
ballerina: deploying service(s) in '/Users/clarkm2/Projects/Ballerina/Weather/weather2.bal'
ballerina: started server connector http-9090
Error getting timestamp
这个想法?如果这是一个缺陷,请在wso2.com JIRA网站上报告这些缺陷吗?
感谢。
答案 0 :(得分:0)
此错误的原因是,$..PERIOD_OF_RECORD.end
返回的元素不是字符串。它返回以下
"PERIOD_OF_RECORD": {
"end": "2017-02-27T21:00:00-0800",
"start": "1969-12-31T16:00:00-0800"
},
无法转换为文字。如果您在catch块中记录异常,您将能够观察到以下错误。
Error getting timestamp : Failed to get string from json. Error while executing jsonpath: The element matching path: $..PERIOD_OF_RECORD.end is not a String.
要记录异常,请将代码修改为:
catch (exception e) {
system:println("Error getting timestamp : " + exceptions:getMessage(e));
}
使用import ballerina.lang.exceptions
import语句。
答案 1 :(得分:0)
尝试更改jsonpath,如下所示:
string timeString = jsons:getString(j, "$.STATION[0].PERIOD_OF_RECORD.end");