grails json转换器只返回字符串而不是数字,整数或双精度

时间:2015-07-30 22:50:01

标签: json grails

我有一个存储简单表结构的数据库表。该表包含用户数据。用户可以定义表的设置方式。因此,我存储值及其类型。一切都是存储表中的字符串。我需要将此作为JSON传递给浏览器客户端,该客户端在JSON上执行一些JavaScript。但是,我想要JSON对象中的数值和字符串值,但Grails JSON转换器只吐出字符串

我的服务有:

def testMap(){
        //my results from a query
        List query = [["name":"price","value":"4.23","type":"double"],["name":"title","value":"box","type":"string"]]

        Map results = [:]
        query.each{ row ->
            if (row.type == "double"){
                results << [(row.name): row.value]
            }
            else
            {
                //what do I do here?
                results << [(row.name): row.value]
            }
        }        
        return results
    }

我的控制器有......

def showMap(){
    render touchSourceSystemService.testMap() as JSON
}

结果是......

{"price":"4.23","title":"box"}

但是我需要价格是数字,而不是像这样的字符串。

{"price":4.23,"title":"box"}

1 个答案:

答案 0 :(得分:0)

我有同样的问题。我能让它发挥作用的唯一方法就是这样......

将此添加到服务类的顶部:

import groovy.json.*

在您的服务方法中,执行以下操作:

def testMap(){
    //my results from a query
    List query = [[name:"price",value:"4.23",type:"double"],[name:"title",value:"box",type:"string"]]
    def slrp = new JsonSlurper()
    def results = [:]
    query.each{ row ->
        if (row.type == "double"){

            //results << ["'${row.name}'": "${row.value}"]
            results  << slrp.parseText('{"' + row.name + '":' +  row.value + '}')
        }
        else
        {
            //what do I do here?
            results << slrp.parseText('{"' + row.name + '":"' + row.value + '"}')
            //results << ["'${row.name}'": "'${row.value}'"]

        }
    }        
    return results
}

你的控制器现在应该返回:

{"price":4.23,"title":"box"}