0

I am following this tutorial: https://spring.io/guides/gs/consuming-rest/ It is consuming a JSON object, like this one:

{
   type: "success",
   value: {
      id: 10,
      quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
   }
}

I have one question. In Value.java, we have two variables:

  private Long id;
  private String quote;

My question is how does Spring know to bind the variable id to the id property in JSON and how does it know to bind quote variable to the quote property in JSON. I tried making both String thinking that maybe Spring auto determines the data-type of a variable and then does the binding but that didn't make a difference. I thought maybe if the variable names are same as the property, that's how it does the binding, so I tried changing the variable names and that didn't make a difference either. Then I thought it is maybe the order of the variables so I switched the variables so it became like this:

  private String quote;
  private String id;

I made them both String on purpose. But still somehow the id property was getting binded to the variable id and quote property to quote variable.

So could someone tell me like how does Spring determine which property to bind to which variable.

2
  • It should go by name, first of the getter/setter methods, then by the property name; if you changed the names but you still got values in all of them then you probably didn't rebuild all of your project. Commented Aug 6, 2016 at 7:12
  • i changed all of the usage of quote to quote1 and id to id1, then did grade build again and then ran the jar file and still got the same output Commented Aug 6, 2016 at 7:36

1 Answer 1

1

Since it's Jackson, default behaviour is to use coresponding getters/setters so my shot is that you changed field name but not getter/setter name.

Sign up to request clarification or add additional context in comments.

2 Comments

So I changed the setters name that didn't make a difference. Then I changed the getters, that made a difference. It returned null then. Do you know why? Why would changing the getters name even make a difference?
Well I am not sure, since I didn't use Jackson a lot. You should check out in this library documentation or maybe this one (not sure if good enogh to answer your question): baeldung.com/jackson-field-serializable-deserializable-or-not Seems like (de)serialization depends on getters name (as far as I know you can change default behaviour of Jackson)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.