JSONObject.toString does not use an Enum's `toString()` but its `name()`

Open Beginner friendly
#838 16 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
78/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
java
Domain
data

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

Fix before the next release

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from stleary/JSON-java

All issues in stleary/JSON-java

Similar issues

More Java issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.