Why Using isSuccess Can Break JSON Serialization in Java
This article explains how different Java JSON libraries handle boolean getter naming, shows code examples of serialization results with fastjson, Gson, and Jackson, and recommends using a plain "success" field with an isSuccess() getter to avoid runtime bugs.
In daily development we often define boolean fields in classes, e.g., a field indicating whether a request succeeded. Naming conventions vary: some use
success, others
isSuccess. According to the JavaBeans Specification, non‑boolean properties use get/set, while boolean properties use
isfor the getter.
For a boolean property
isSuccess, the getter should be
isSuccess()and the setter
setSuccess(boolean). However, IDEs may generate
isSuccess()and
getSuccess(), leading to ambiguity.
<code>public <PropertyType> get<PropertyName>();
public void set<PropertyName>(<PropertyType> a);
</code> <code>public boolean is<PropertyName>();
public void set<PropertyName>(boolean m);
</code>When serializing objects, different JSON libraries apply different strategies. fastjson and Jackson inspect getters, treating
isSuccess()as a property named
success, producing JSON
{"success":true}. Gson inspects fields directly, yielding
{"isSuccess":true}. Consequently, deserializing fastjson’s output with Gson results in the boolean remaining false.
<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> <code>public class BooleanMainTest {
public static void main(String[] args) throws IOException {
Model model = new Model();
model.setSuccess(true);
System.out.println("Serializable Result With fastjson :" + JSON.toJSONString(model));
Gson gson = new Gson();
System.out.println("Serializable Result With Gson :" + gson.toJson(model));
ObjectMapper om = new ObjectMapper();
System.out.println("Serializable Result With jackson :" + om.writeValueAsString(model));
}
}
</code>This discrepancy can cause serious bugs in production. The recommended practice is to name the field
successand keep the getter
isSuccess(), fully complying with JavaBeans rules and ensuring consistent behavior across 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.