java – How to pass a list of an object that contains another object (composition) to a JSON

Question:

I have two classes: Contact and Operator. A in the Contact class I have a composition: private Operadora operadora ; I have a DAO where I have a class that returns a list of Contacts, in the console the list is displayed like this:

[Contato [nome=Diego Augusto, telefone=3525-4566, data=Mon Sep 14 13:43:42 BRT 2015, operadora=Operadora [nome=Tim, codigo=41, categoria=Celular, valor=2]]]

But when I try to pass this query to the method that serializes the JSON the result is this:

{
nome: "Diego Augusto"
telefone: "3525-4566"
data: "2015-09-14T13:50:16-0300"
}

How can they see the operator is not displayed, how can I display the operator in JSON?

My controller:

@Controller
@Path("/contato")
public class ContatoController {
    @Inject
    private Result result;
    @Inject
    private ContatoDAO contatoDAO;

    @Get
    @Path("/contatos")
    public void listAll() {
        System.out.println("TESTE: "+contatoDAO.lista());
        result.use(Results.json()).withoutRoot().from(contatoDAO.lista()).serialize();
    }

}

DAO:

//Testando...
public List<Contato>lista(){
        List<Contato>listaContatos = new ArrayList<>();
        Contato c = new Contato();
        Operadora o = new Operadora();

        c.setNome("Diego Augusto");
        c.setData(new Date());
        c.setTelefone("3525-4566");

        o.setCodigo(41);
        o.setNome("Tim");
        o.setCategoria("Celular");
        o.setValor(new BigDecimal(2));
        c.setOperadora(o);

        listaContatos.add(c);


        return listaContatos;
    }

Answer:

I solved the problem by adding an include("operadora") to the result this:

result.use(Results.json()).withoutRoot().from(contatoDAO.lista()).include("operadora").serialize();
Scroll to Top