7

I am trying to create simple webservice, that is reading JSON from URL and gives it back. I followed spring.io tutorial about this. I am probably missing something about naming conventions?

JSON I use doesn't have nice naming convention. Some values are in uppercase, some lowercase other are mixed. What I understood for proper matching with restTemplate I need to follow these names.

My object structure:

public class Page {
private String name; //works
private String about; // works
private String PHONE; //does not work
private String Website; //does not work

//getters and setters
}

If I change them to public, they start to work.

public class Page {
private String name; //works
private String about; // works
public String PHONE; //works
public String Website; //works

//getters and setters
}

This is the part of code where I use that

@RequestMapping(value = "/Test")
public Bubble getBubbleInfo(){
RestTemplate restTemplate = new RestTemplate();
Page page= restTemplate.getForObject("myURL", Page.class);
    return page;
}

What I am missing? It looks that using private required classical lowerUpper convention but if I change that it won't be properly matched with the JSON. Can I name it somehow for spring?

//spring, this is PHONE
public String phone;

Thanks a lot.

Elis.jane
  • 259
  • 2
  • 4
  • 10

1 Answers1

17

You can use @JsonProperty annotation to override the variable name.

@JsonProperty("phone")
public String PHONE;
Mithun
  • 7,747
  • 6
  • 52
  • 68
  • Thanks, I tried that but in the result I had:both PHONE and phone. When I removed getters and setters it seems to be working. It means I should not have setters there? Or it is caused by something else? – Elis.jane Nov 13 '14 at 08:46
  • have you added the annotation to the getter/setter method as well? – Mithun Nov 13 '14 at 09:10
  • Basically, if its private then have getter and setter and annotate the variable declaration. Else, just annotating the variable declaration should fix it. – Mithun Nov 13 '14 at 09:17
  • Thanks! This solution worked. Just put @JsonProperty annotation on variable, getters, and setters and your restful can consume as well as produce the uppercase! – Akshay Thorve Apr 23 '18 at 02:41
  • Thanks a lot for this answer, helped me – excelsiorious Jan 07 '21 at 03:02