在Spring表达式语言中将String转换为Double

时间:2015-06-22 05:34:57

标签: spring hashmap type-conversion spring-el

我对春天的表达语言很陌生。我有一个包含值为字符串的地图。

{
 "id": "1",
 "object": {
  "object1": {
    "fields": {
      "value1": {
         "value":"3"
      },
      "value2": {
         "value":"2"
      }
    }
  }
 }
}

我的春天表达看起来像这样,

((object['object1'].fields['value1'].value * object['object1'].fields['value2'].value) * 0.5)

我的计算方法如下所示,其中SampleObject类具有地图对象

public Double calculation(String expression, SampleObject sampleObject){
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(expression);
    Double evaluatedValue = (Double)exp.getValue(sampleObject);
    return evaluatedValue;
}

由于值是字符串,我收到一条错误,指出无法将String转换为Double。如果我像这样改变表达式

,这可以消除
((new Double(object['object1'].fields['value1'].value) * new Double(object['object1'].fields['value2'].value)) * 0.5)

但我正在寻找一种解决方案,我无需更改表达式或对象。有解决方案吗?

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以插入一个支持对这些操作数类型进行操作的类:

class StringDoubleOperatorOverloader implements OperatorOverloader {

    @Override
    public boolean overridesOperation(Operation operation, Object leftOperand,
            Object rightOperand) throws EvaluationException {
        return operation==Operation.MULTIPLY && 
               leftOperand instanceof String && 
               rightOperand instanceof String;
    }

    @Override
    public Object operate(Operation operation, Object leftOperand, Object rightOperand)
            throws EvaluationException {
        Double l = Double.valueOf((String)leftOperand);
        Double r = Double.valueOf((String)rightOperand);
        return l*r;
    }

}

然后将自定义的StandardEvaluationContext传递给getValue()

    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(expression);

    StandardEvaluationContext sec = new StandardEvaluationContext();
    sec.setOperatorOverloader(new StringDoubleOperatorOverloader());

    Double evaluatedValue = (Double)exp.getValue(sec,new SampleObject());

答案 1 :(得分:0)

由于您的JSON具有value1.valuevalue2.value作为String,因此Expression会抛出异常。

将您的JSON更改为具有十进制值

{
 "id": "1",
 "object": {
  "object1": {
    "fields": {
      "value1": {
         "value":3.0
      },
      "value2": {
         "value":2.0
      }
    }
  }
 }
}

或者在Expression方法中,而不是强制执行解析。

public Double calculation(String expression, SampleObject sampleObject){
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(expression);
    Double evaluatedValue = Double.parseDouble(exp.getValue(sampleObject).toString()); // This line
    return evaluatedValue;
}