Gson Return Array of One Position

Asked

Viewed 78 times

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 the 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);
                        }
                    });
...

1 answer

1


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

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

Using scapes for the string to go with the quotes.

  • I’m trying and still not returned anything,

  • The data saves, but does not return anything

  • Check the browser console for the status of the request, there may be an error there..

  • No error appeared. Type in json I used JSONObject json = new JSONObject();
 JSONArray jsonArray = new JSONArray(); json.put("retorno", "0");

 jsonArray.put(json);
 out.print(json.toString()); but in gson I don’t know

  • 1

    It worked, it was my javascript that Return false was in the wrong place

Browser other questions tagged

You are not signed in. Login or sign up in order to post.