今天有个任务,要把redis中缓存的json串读取出来并放到对象中,便于后续使用对象。相关代码如下:
json串
{
"GDS_ID":"123","GDS_NAME":"手机" }
对象定义
class TGdsInfo {
def gdsId
def gdsName
}
完整代码
import groovy.json.JsonSlurper
/** * Created by fangyunfeng on 2015/9/12. */
def gdsInfo = ''' { "GDS_ID":"123","GDS_NAME":"手机" } '''
class TGdsInfo {
def gdsId
def gdsName
}
/** * json串字段名到对象属性名映射函数 * @param s * @return */
def camle(String s){
return s.toLowerCase()
.replaceAll("_[A-Za-z]"){String it->it.toupperCase()}
.replace('_','')
}
def gdsJson = new JsonSlurper().parseText(gdsInfo)
def gdsObj = new TGdsInfo()
gdsJson.each {Map.Entry entry -> String propName = camle(entry.key)
if(gdsObj.MetaClass.hasProperty(gdsObj,propName)){
gdsObj[propName] = entry.value } } println("gdsId:"+gdsObj.gdsId) println("gdsName:"+gdsObj.gdsName)
输出结果
gdsId:123
gdsName:手机
Process finished with exit code 0