简体   繁体   English

Grails的。 域类。 Json字符串问题

[英]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: 我需要创建一个字符串JSON,它只包含有关这些字段的信息:

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. 但是在JSON字符串中我拥有所有数据:(债务,前额,证券...也在字符串内。但是我不需要此数据。

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 您将必须使用json构建器来解决此问题

sample from a blog 来自博客的样本

Grails JSON Builder Documentation Grails JSON Builder文档

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: 您可以尝试将JSON上的setRenderDomainClassRelations设置为false,但我想您真正需要的是使用构建器并进一步明确声明JSON结构:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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