Treating null Pointer Exception

Asked

Viewed 708 times

0

I’m getting, in my back end, a json object from the screen this way:

{
    "pessoa": {
        "nome": "aa",
        "nomeSocial": "aa",
        "tipoPessoa": "F",
        "nomePai":"",
        "dataNascimento": "15/06/1983",
        "nomeMae": "a"
    },
    "cns": "aa",

    "pessoasEnderecos": {
        "cep": "a", 
        "nomeLogradouro": "a",
        "nomeBairro": "a"
    }
}

The point is I’m having a nullPointerException because, of course, my json nomePai is empty, as I do to treat this error and persist the data in the database by passing the null namePai, since it is not required by the business rule?

There are several attributes that fit this rule, I put only one for demonstration.

My method:

@RequestMapping(method = RequestMethod.POST, value = "/pacientes")
    public HttpStatus cadastrarPacientes(@RequestBody ObjectNode json) throws ParseException  {

        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");

            entidades.setIdEntidade(json.get("pessoa").get("entidade").get("idEntidade").asLong());

            Pessoas pessoas = new Pessoas();
            pessoas.setNome(json.get("pessoa").get("nome").textValue());
            pessoas.setNomeSocial(json.get("pessoa").get("nomeSocial").textValue());

            pessoas.setNomePai(json.get("pessoa").get("nomePai").textValue());
            pessoas.setNomeMae(json.get("pessoa").get("nomeMae").textValue());
            pessoas.setDataNascimento(formato.parse(json.get("pessoa").get("dataNascimento").textValue()));

            pessoas.setTipoPessoa(json.get("pessoa").get("tipoPessoa").textValue());
}
  • pessoas.setNomePai(json.get("pessoa").get("nomePai") == null ? 
 null : json.get("pessoa").get("nomePai").textValue());

  • @Articuno worked !! Post your comment as reply. Thank you !

  • @Article Worked only for the values in String.. in this case, for example;; entidades.setIdEntidade(json.get("pessoa").get("entidade").get("idEntidade").asLong()); keeps giving error..

  • There you have to read the documentation of the method asLong and see what kind of return it gives when nothing is returned. I don’t know what api you’re using, so there’s no way to suggest anything. Take a look at the documentation of this method and anything else, post the doc link here if you are in doubt.

1 answer

2


A simple resolution would be to use a ternary transaction to prevent the attempt to access a null return:

pessoas.setNomePai(json.get("pessoa").get("nomePai") == null ? null : json.get("pessoa").get("nomePai").textValue());

Thus, the null return is maintained if the returned value is empty, but the textValue() will only be called if it is not null.

Browser other questions tagged

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