Why Using isSuccess Can Break JSON Serialization in Java and How to Fix It
This article explains how different Java boolean naming conventions affect JSON serialization across fastjson, Gson, and Jackson, demonstrates the resulting inconsistencies with code examples, and recommends using a plain "success" field with an isSuccess getter to ensure reliable cross‑library behavior.
In daily development we often define boolean fields in classes, e.g., a field indicating whether a request succeeded.
Developers use different naming conventions such as
successor
isSuccess, and IDEs often generate
isSuccessgetters automatically.
According to the JavaBeans Specification, a normal property
propertyNamehas getters/setters
getPropertyName()and
setPropertyName(...). For boolean properties the getter is
isPropertyName()and the setter remains
setPropertyName(...).
<code>public <PropertyType> get<PropertyName>();
public void set<PropertyName>(<PropertyType> a);
</code>For a boolean property the signatures become:
<code>public boolean is<PropertyName>();
public void set<PropertyName>(boolean m);
</code>If the property is named
success, the getter should be
isSuccess(or
getSuccess) and the setter
setSuccess. If the property itself is named
isSuccess, the getter would be
isIsSuccessor
getIsSuccess, which is confusing.
Consider the following JavaBean:
<code>class Model implements Serializable {
private static final long serialVersionUID = 1836697963736227954L;
private boolean isSuccess;
public boolean isSuccess() { return isSuccess; }
public void setSuccess(boolean success) { isSuccess = success; }
public String getHollis() { return "hollischuang"; }
}
</code>When this class is serialized with different JSON libraries, the results differ:
<code>Serializable Result With fastjson :{"hollis":"hollischuang","success":true}
Serializable Result With Gson :{"isSuccess":true}
Serializable Result With jackson :{"success":true,"hollis":"hollischuang"}
</code>Fastjson and Jackson inspect getter methods, treat
isSuccessas a property named
success, and therefore output
"success". Gson, on the other hand, inspects fields directly and outputs the original field name
"isSuccess".
Consequently, if an object serialized by fastjson (or Jackson) is deserialized by Gson, the
isSuccessfield will be missing and default to
false, which can cause serious bugs in production.
To avoid this inconsistency, the recommendation is to name the field
successand keep the getter
isSuccess. This follows the JavaBeans convention and yields identical results across all major JSON serialization frameworks.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.