Skip to content

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

Open
@arthurBricq

Description

@arthurBricq

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions