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

オープン 初心者向け
#838 コメント 16 件 リアクション 3 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
78/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
java
領域
data

調査の方向性

Issue がシリアライズの経路として特定している src/main/java/org/json/JSONObject.java の 2656 行目付近から始めます。提供されている TestEnumToString の再現コードを実行し、enum フィールドがどのように変換されるかを確認します。JSONObject.toString() が enum のオーバーライドされた文字列表現を尊重し、再現コードが期待される値を生成すれば完了です。

索引モデルが issue の本文から書いたものです。

説明

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

主要言語
Java
スター
4.7k
フォーク
2.6k
平均マージ
11日 18分
マージ済み PR(30日)
1

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

stleary/JSON-java のほかの issue

stleary/JSON-java の issue をすべて見る

似ている issue

Java の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。