简体   繁体   中英

Grails. Domain class. Json string problem

i have this domain class:

package test

class Credit {


    String office;
    String branch;
    String name;
    Integer code;
    Integer number;
    Integer term;
    Integer amount;
    Integer rate;


    static hasMany = [  debts : Debt, 
                fronts : Front,
                securities : Security,
                lawyers : Lawyer,
                guarantes : Guarante]


    static constraints = {
    }
}

I need to create a string JSON, which contains only information about these fields:

String office;
        String branch;
        String name;
        Integer code;
        Integer number;
        Integer term;
        Integer amount;
        Integer rate;

I try:

rezult = Credit.list(fetch:[debts:"lazy", fronts: 'lazy', securities: "lazy", lawyers:"lazy", quarantes:"lazy"])
render new JSON(success: true, message: 'ok', data:rezult);

but in JSON string i have all data :( debts, fronts, securities... inside string too. but i not need this data.

How I do avoid using them?

ANSWER:

render(contentType:"text/json") {
    success=true
    message='ok'
    totalCount=Credit.count()
    data = array {
        for(d in results) {
            data    office:d.office,
                    branch:d.branch, 
                    name: d.name,
                    code:d.code, 
                    number:d.number,
                    term:d.term,
                    amount:d.amount,
                    rate:d.rate
        }
    }   
}

you are going to have to use the json builder to solve this problem

sample from a blog

Grails JSON Builder Documentation

You could try and set setRenderDomainClassRelations on JSON to false but I suppose what you really need is to use a builder and explicitly declare the JSON structure further:

render(builder:'json') {
  success(true)
  message('ok')
  data {
    office(rezult.office)
    branch(rezult.branch)
    // and so on
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM