I’ve just tried that but I still can’t preform any math on the value
rule "Convert JSON"
when
Item StudyLight_String changed
then
val String sJson = '{"state":"ON","brightness":255}'
val Number nBright = transform("JSONPATH","$.brightness",sJson)
val Number converted = (nBright * 100)
logInfo("User.Testing","Converted = " + converted)
end
When the rule runs I get this error in the log.
2019-03-19 18:07:06.987 [ERROR] [ntime.internal.engine.RuleEngineImpl] - Rule 'Convert JSON to Item Type Number': An error occurred during the script execution: Could not invoke method: org.eclipse.smarthome.model.script.lib.NumberExtensions.operator_multiply(java.lang.Number,java.lang.Number) on instance: null
rule "Convert JSON"
when
Item StudyLight_String changed
then
val String sJson = StudyLight_String.state
val Number nBright = transform("JSONPATH","$.brightness",sJson)
logInfo("User.Testing","nBright = {}", nBright)
if(!(nBright instanceof Number)) return;
val Number converted = nBright * 100
logInfo("User.Testing","Converted = {}", converted)
end
2019-03-19 18:26:00.089 [ERROR] [ntime.internal.engine.RuleEngineImpl] - Rule 'Convert JSON': An error occurred during the script execution: Could not invoke method: org.eclipse.smarthome.core.transform.actions.Transformation.transform(java.lang.String,java.lang.String,java.lang.String) on instance: null
Thanks your for help.
EDIT
Changing the rule to the following stopped the error but it stops at the If.
rule "Convert JSON"
when
Item StudyLight_String changed
then
val String sJson = StudyLight_String.state.toString
val Number nBright = transform("JSONPATH","$.brightness",sJson)
logInfo("User.Testing","nBright = {}", nBright)
if(!(nBright instanceof Number)) return;
val Number converted = nBright * 100
logInfo("User.Testing","Converted = {}", converted)
end
In VS Code, this statement generates the error Type mismatch: Cannot convert from String to Number
I usually deal with it this way in my rules.
val Number nBright = Integer.parseInt(transform("JSONPATH","$.brightness",sJson))
If there’s a chance the return from transform will be non-numeric, you would want to catch NumberFormatException.
try {
val Number nBright = Integer.parseInt(transform("JSONPATH","$.brightness",sJson))
} catch (NumberFormatException e) {
// Do something if the value in non-numeric
}