skip to Main Content

What are the differences of letting spring bind JSON objects to Custom Pojos vs retrieving the response as a JSON string and using the ObjectMapper to parse?

We had some legacy code that called an api and got a response as a JSON string. The code then went ahead and parsed the data into the new POJO objects.

I was working on improving that area of the code and added some new functions, but I followed the legacy code to reuse the old helper functions to make things consistent.

However, when I submitted it for review, my supervisor asked whether I can get it to skip the manual parsing, and get the JSON to deserialize into the POJO object. He said: "…it would be nicer if you could…."

I got this completed, but I never heard why this is "better" than using the Object Mapper.
Here is an example: (It’s something like this, not exact, just basing this off memory

  • Legacy Code:
String response = someCall();

Try {
  SomePojo object = ObjectMapper.parse(response ,SomePojo.class)
  // Some helpers that extract a list of data from this object, error catching etc.
  List<SomeData> data = object.getData().stream(//helpers to map etc);
  return data;
}
  • Then the new version is:
try {
 SomePojo object = someCall()
 return object.getData()
}

From what I was reading up, this method is still using the same Jackson objectmapper to parse, and it uses the getters and setters from the POJO object.

Other than the fact that it looks cleaner, I couldn’t really figure out why this is a better approach.

Any thoughts?

2

Answers


  1. To my understanding, you’re talking about spring web feature to deliver you an object from payload in a transparent way, right?

    If yes, then the key benefit is not to have the serialization/deserialization code visible to you.

    On the other hand, if you’re not sure about the payload shape then it can be troublesome, since spring will convert it into Exceptions/BAD_REQUESTS that will happen even before it enters on your code.

    In most cases it’s ok, because the payload is expected to be known. Besides that, it’s just a matter to keep doing the parse by yourself or the let the framework do the job for you.

    Login or Signup to reply.
  2. Spring behind the scenes uses the Json-Jackson library (ObjectMapper class) to marshal data between POJOs and JSON. This could be configured so you can tell Spring to use any other library, bu by default it uses Jackson. So, Letting Spring do the conversion is just cleaner than you doing it yourself. As for efficiency you don’t get much of the benefit either way, but still if you can let Spring do it it is cleaner and it is done uniformly. So, Unless you have a special requirement for your POJO conversion that doesn’t come with Spring out of the box, I would side with your manager and say let Spring do it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search