JSONObject.toString does not use an Enum's `toString()` but its `name()`
Nobody has claimed this yet.
Assessment
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Newbie friendliness
- 78/100
Research direction
Start in src/main/java/org/json/JSONObject.java around line 2656, which the issue identifies as the serialization path. Run the supplied TestEnumToString reproduction and inspect how enum fields are converted. Done means JSONObject.toString() respects an overridden enum string representation and the reproduction produces the expected values.
Written by the indexing model from the issue text.
Description
When calling the toString method of a JSONObject, if a field of the object is an enum, the name method is called (when constructing the string) instead of the toString method. This is problematic as name() is not overidable (as it is decalred final) whereas toString is.
I have found where this is in the sources.
Furthermore, it is specified in the java doc of the name function :
Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name
The fix should be really easy, I can do it if it helps you. Is this an issue not tracked ? I have not found corresponding issues.
Here's a quick way to reproduce this default.
public class TestEnumToString {
enum MyEnum {
V_1, V_2;
@Override
public String toString() {
switch (this) {
case V_1:
return "1.0";
case V_2:
return "2.0";
};
return "";
}
}
public static void main(String[] args) throws JSONException {
JSONObject json = new JSONObject();
json.put("v1", MyEnum.V_1);
json.put("v2", MyEnum.V_2);
System.out.println(json.toString());
}
}
Thanks in advance,
Arthur
- Dominant language
- Java
- Stars
- 4.7k
- Forks
- 2.6k
- Avg merge
- 11d 18m
- Merged PRs (30d)
- 1
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from stleary/JSON-java
-
Fix before the next release
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
-
Active discussion
Difficulty 5/5 Over a week Newbie friendliness 35/100
All issues in stleary/JSON-java
Similar issues
-
Bug Java Platform: Java
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
getsentry/sentry-java#6138 · 1 comment ·
-
bug needs triage p2
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
GoogleCloudPlatform/DataflowTemplates#4273 · 1 comment ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
-
bug needs triage
Difficulty 2/5 1-3 hours Newbie friendliness 76/100