I’m trying to display a table listing the Country codes (iso3166) in a postgresql db onto an html page using Spring Boot and Angular, the parameter name in the http response lists "number" when instead I want it to list "nbr".
The SQL table has 4 columns
- name (varchar) unique
- alpha2 (varchar) PK unique
- alpha3 (varchar) unique
- nbr (int4)
My Spring Boot Models is the following:
@Entity
@Table(name = "iso3166")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String alpha2;
@Column(name = "name")
private String name;
@Column(name = "alpha3")
private String alpha3;
@Column(name = "nbr")
private int nbr;
public Country()
{
}
public Country(String name, String alpha2, String alpha3, int nbr)
{
this.name = name;
this.alpha2 = alpha2;
this.alpha3 = alpha3;
this.nbr = nbr;
}
/*
getters and settings + toString()
*/
The repository uses JPARepository
public interface ICountryRepository extends JpaRepository<Country, String> {
}
And the Controller has only the findAll() method
@RestController
@RequestMapping({"/api"})
public class CountryController {
@Autowired
ICountryRepository countryRepository;
@GetMapping
public List<Country> findAll(){
List<Country> country = countryRepository.findAll();
return country;
}
}
Running spring-boot and opening localhost in chrome, the table shows up just fine.
However, looking at the Response tab under Network, it shows up like this
Shows the same thing if I go to http://localhost:8080/api
Why does the Http Response return the "nbr" field as "number" instead? And how can I change it to show up as "nbr" in the Http response? Does something happen in the background in Spring Boot when formulating the http response that I can’t control?
2
Answers
Found out what happened, although I don't know the specifics.
spring uses Jackson to serialize, and Jackson uses by default public getters to serialize and name data. Since I named the nbr getter/setters as getNumber() and setNumber, changing it to getNbr() and setNbr() respectively solved the issue.
It is a number because you defined it as a number here, in Country entity:
The best solution is to create another object which is used for HTTP communication. For example:
CountryDTO
.In CountryDTO you can define
nbr
field as String.Then you just have to create a mapping between Country and CountryDTO objects.
Why you should always do like this: