Gson Return Array of One Position

2

Hello

I have the method:

@RequestMapping("/olaMundo")
    public String iniciando(Model model, Cadastro cadastro){
        CadastroDAO dao = new CadastroDAO();
        dao.adiciona(cadastro);
        model.addAttribute("nome",cadastro.getNome());
        Gson gson = new Gson();

        String retorno = gson.toJson("{'nome' :'"+ cadastro.getNome()+"'}");
        return retorno;
    }

I would like gson to return type

 "{'nome' : 'Maria'}"

In my javascrip return the name

...
$.ajax({
                        type:  'post',
                        url:   'olaMundo',
                        dataType: 'json',
                        data: {
                            nome     : nome,
                            endereco : endereco,
                            telefone : telefone,
                            email    : email
                        },
                        success: function(data){
                           alert(data.nome);
                        }
                    });
...
    
asked by anonymous 04.04.2017 / 20:16

1 answer

1

You do not need to use Gson for this. You can do:

 return "\"{'nome' :'"+ cadastro.getNome()+"'}\"";

Using scapes for the string to go with the quotation marks.

    
04.04.2017 / 20:33