1

I want to build a json from a list of objects. So far I am able to produce only 1 object into json. What am i missing? Is there a better way to transform list of objects into json?

private static List<ProductAlertsResponse> executeSelection(String query)
{
    List<ProductAlertsResponse> prodAlerts=new ArrayList<ProductAlertsResponse>()
    sql.eachRow(query)
    {
        ProductAlertsResponse prodAlert=new ProductAlertsResponse((String)it.id,(String)it.name,(String)it.description,(String)it.active,(String)it.release_date)

        //I was converting it into a List before, but then I thought it would be better to do with list of classes
        /*String[] rows=new String[5]
        rows[0]=(String)it.id
        rows[1]=(String)it.name
        rows[2]=(String)it.description
        rows[3]=(String)it.active
        rows[4]=(String)it.release_date

        result.add(rows)*/

/*Also feel free to comment is this right way to put in list (above commented code)*/

        prodAlerts.add(prodAlert)
    }
    return prodAlerts
}

static main(args) {
    AppProperties.load()
    sql= Sql.newInstance("jdbc:oracle:thin:@"+AppProperties.get("hostname")+":"+AppProperties.get("port")+":"+AppProperties.get("service"), AppProperties.get("username"), AppProperties.get("password"),"oracle.jdbc.OracleDriver")

    List result=executeSelection("select ID,NAME,DESCRIPTION,ACTIVE,RELEASE_DATE from productinfo where ACTIVE='A'")

    def builder = new groovy.json.JsonBuilder()

    def root=builder.response{

        product_alerts{
            result.each{
                //JsonOutput.toJson(it)
                id  it.getId()
                name it.getName()
                description it.getDescription()
                active it.getActive()
            }

        }

    }
    println builder.toPrettyString()
}

My output

{
    "response": {
        "product_alerts": {
            "id": "6",
            "name": "ABC1",
            "description": "Test2",
            "active": "A"
        }
    }
}

1 Answer 1

4

Use def builder = new groovy.json.JsonBuilder(result)

Update

Try this

def json = new groovy.json.JsonBuilder()
def result1 = json {
     response result
}
println json.toPrettyString()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks.. at the least it is now transforming all the objects into json. What if I want to have a root tag response?
Just a tip, another way if you simply need to add the root node is to use: new groovy.json.JsonBuilder([response: result]).
@OverZealous: Thanks nice tip, also can you please take a look at a continuation question here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.