Jackson and json array

Asked

Viewed 285 times

0

All right, guys? I’ve been racking my brain for a few days now but to no avail.

I need to insert in the BD information that comes through JSON. It turns out that when an array comes, it doesn’t want to insert.

Explain better:

In the domain, I have the client class:

@Entity
public class Cliente
private String nome;
@ManytoMany
private List<Telefone> telefones = new ArrayList<>();

public Cliente() {}

getters e setters 

And I got the phone class:

@Entity
public class Telefone
private String numero;
@JsonIgnore
@ManytoMany
private List<Cliente> clientes = new ArrayList<>();

public Telefone () {}

getters e setters

I created a DTO Client class:

public class ClienteDTO
private String nome;
private String numero;

public ClienteDTO () {}

getters e setters

and in service I created the Clienteservice class that in addition to some methods has the following method:

public Cliente converteDoDTO(ClienteDTO clienteDTO) {

Cliente c = new Cliente(clienteDTO.getNome());
Telefone t = new Telefone(clienteDTO.getNumero());

c.getTelefones().addALL(Arrays.asList(t));
t.getClientes().addALL(Arrays.asList(c));

}

That way if I pass JSON that way:

{
  "nome" : "Teste",
  "telefone" : "123"
}

Will be included in the comic.

But I’d like it to be this way:

{
  "nome" : "Teste",
  "telefones" : 
 [
   {"telefone" : "123"},
   {"telefone" : "456"},
   {"telefone" : "789"}
 ]
}

Only if you do this, the "phones" comes empty. And only the name is entered in the bank. I searched and saw that I have to use the Objectmapper, more or less like this:

ObjectMapper mapper = new ObjectMapper();
List<Telefone> telefones = mapper.readValue(jsonInput, new TypeReference<List<telefone>>(){});

I don’t know where to create it. If it’s in the serivce, in the DTO, in the Domain. I am very lost. Could anyone help? Thank you already.

  • 1

    Your model telefones:telefone remembers much more XML than JSON itself. A more idiomatic model in this notation would be "telefones": [ "123", "456", "789" ]

  • The problem is that I have more information than just number. My phone looks like this: { "numeroDeTelephone" : "1", "typeDeelephone" : 2}

1 answer

1


In order for a class attribute to be serialized, it must have the annotation @Jsonproperty or have the access function get

In this case, just write the note on DTO passing a Collection.

@JsonProperty("telefones")

Browser other questions tagged

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