将json添加到groovy中的json中

时间:2015-10-01 14:22:27

标签: json groovy

我是groovy的新手。我的要求是我必须将json附加到json.My代码中,如下所示:

我构建的JSON:

def builder = new groovy.json.JsonBuilder()
   def root=builder.event{                
            type  "model_output_load_init"
            time new Timestamp(date.getTime())
            status "success"                        
        }

来自DB的JSON:

def json = rs.getString("status");

现在我必须将构造附加到JSON From DB中。请帮助我解决这个问题。谢谢。

编辑:

我的构建JSON:

{
    "event": {
        "type": "model_output_load_init",
        "time": "2015-10-01T14:08:17+0000",
        "status": "success"
    }
}

JSON FROM DB:

{
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    }
}

需要输出:

{
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "event": {
        "type": "model_output_load_init",
        "time": "2015-10-01T14:08:17+0000",
        "status": "success"
    }

}

1 个答案:

答案 0 :(得分:1)

您可以附加到JsonSlurper生成的地图。

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def builder = new JsonBuilder()
def root = builder.event{                
    type  "model_output_load_init"
    time new Timestamp(date.getTime())
    status "success"                        
}

// Simulates the JSON from DB
def json = new JsonSlurper().parseText('''
{
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    }
}''')

// Append the built JSON to the "slurped" JSON
json.event = root.event

// Re-build the JSON so it can saved as a String
new JsonBuilder(json).toPrettyString()

输出如下:

{
    "event": {
        "type": "model_output_load_init",
        "time": "2015-10-01T14:39:11+0000",
        "status": "success"
    },
    "modelExec": {
        "Initialized": {
            "Timestamp": ""
        }
    },
    "model_build": {
        "Initialized": {
            "Timestamp": ""
        }
    }
}