Jack
Jack

Reputation: 67

ArrayList<Object> JSON

I've this two classes on backend:

Produto

public class Produto implements Serializable {

    @Transient
    @JsonSerialize
    @JsonDeserialize
    private Set<Filial> filials = new HashSet<>();

//more fields
//getters and setters

Filial

public class Filial implements Serializable {

@Id
private Long id;

@Column(name = "nm_filial")
private String nmFilial;

//more fields
//getters and setters

The filiais property isn't a database field and receives its value this way:

 @RequestMapping(value = "/produtos/{id}",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Produto> getProduto(@PathVariable Long id) {

    Produto produto = produtoService.findOne(id);

    Set<Filial> filials = produtoFilialService.findFiliaisByIdProduto(produto.getId());     
    produto.setFilials(filials);

    return Optional.ofNullable(produto)
        .map(result -> new ResponseEntity<>(
            result,
            HttpStatus.OK))
        .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

But when a call this class on frontend, the JSON returned is like this:

{"id":1, "filials":[[1,"A"],[2,"AS"]]}

How can I return a array of object like this:

{"id":1, "filials":[{"id":1, "nmFilial":"A"},{"id":2, "nmFilial":"AS"}]}

?

Upvotes: 0

Views: 87

Answers (2)

Levy Moreira
Levy Moreira

Reputation: 2773

Here work with the follow configuration:

In my Entity:

    @Transient
    @JsonSerialize
    @JsonDeserialize
    private List<Filial> filiais = new ArrayList<>();

The Filial class:

import java.io.Serializable;


public class Filial implements Serializable{

    private Long id;

    private String nmFilial;

    public Filial(){}

    public Filial(Long id, String nmFilial){
        this.id = id;
        this.nmFilial = nmFilial;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNmFilial() {
        return nmFilial;
    }

    public void setNmFilial(String nmFilial) {
        this.nmFilial = nmFilial;
    }
}

On repository:

@Query(value = "SELECT pf.filial FROM ProdutoFilial pf "
        + "where pf.produto.id = :idProduto")
ArrayList<Filial> findFiliaisByIdProduto(@Param("idProduto") Long idProduto);

In my service I do (just to test)

produto.getFiliais().add(new Filial(1l, "a"));
produto.getFiliais().add(new Filial(2l, "b"));

And work:

...
  "filiais": [
    {
      "id": 1,
      "nmFilial": "a"
    },
    {
      "id": 2,
      "nmFilial": "b"
    }
  ]
}

Upvotes: 1

Mustapha Larhrouch
Mustapha Larhrouch

Reputation: 3393

use an ArrayList instead of HashSet :

public class Produto implements Serializable {

    @Transient
    @JsonSerialize
    @JsonDeserialize
    private List<Filial> filials = new ArrayList<>();

Upvotes: 0

Related Questions