WHAT THE HELL IS WRONG WITH SPRING BOOT!? Can’t convert boolean to JSON correctly! + SOLUTION

Rakesh Narang
2 min readJan 18, 2020

Follow me on insta: https://www.instagram.com/global.software.developers/?hl=en

Introduction

Spring Boot is a preferred choice among backend developers who code in Java. The reason is that it is very easy to pickup and lets web developers build production grade restful web services in no time.

Problem

Recently in one my projects I faced this problem.

Sometimes we have boolean conditions in our models. And most of the times the boolean condition starts with “is.”

For example: -

Let us a take a Person model.

Is a person married? would map to: -

private boolean isMarried

Is a person Indian? would map to: -

private boolean isIndian

Does this make sense?

Ideally, when an object of this class is converted to JSON, the result should be: -

But in Spring Boot, the result is: -

WHY IS THAT SPRING BOOT!? WHAT IS WRONG WITH YOU!?

ANOTHER PROBLEM

Do you know about ObjectMapper?

Is is a class in databind package of Jackson library.

It converts Java objects to JSON. But even that library is converting it incorrectly.

return new ObjectMapper.writeValueAsString(new Person());

returns the following String: -

{ “indian”: false, “married”: false }

SOLUTION + ANOTHER SPRING BOOT BUG

Okay!

So the solution to this problem is to use @JsonProperty annotation at the top of the member variable so to tell spring boot to use that value as JSON key instead of the variable name.

How does that look like?

public class Person {@JsonProperty(“isMarried”)
private boolean isMarried;
@JsonProperty(“isIndian”)
private boolean isIndian;
}

But does this work?

It does.

But is the result perfect?

Nopes!

When you add these annotations, here’s the result?

{ “indian”: false “married”: false “isIndian”: false “isMarried”: false}

Yupp! Spring boot, and ObjectMapper, both result in the response above, which won’t cause a problem in your app, but what is the need of sending useless, redundant data in the response of an API.

THE CORRECT SOLUTION

The correct solution to the above problem is to annotate getter methods instead of member variables.

Here’s how: -

public class Person {private boolean isMarried;private boolean isIndian;@JsonProperty(“isMarried”)
public boolean getIsMarried() {
return this.isMarried;
}
@JsonProperty(“isIndian”)
public boolean getIsIndian () {
return this.isIndian;
}
}

After you annotate your model as above, you are going to get correct response from your API: -

{“isIndian”: false“isMarried”: false}

CONCLUSION

I hope this tutorial was useful.

If you have something to say, please put down your thoughts in the comments section below.

Thanks . :)

Follow me on insta: https://www.instagram.com/global.software.developers/?hl=en

--

--