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

Aperta Adatta ai principianti
#838 16 commenti 3 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
78/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
java
Ambito
data

Direzione di ricerca

Inizia in src/main/java/org/json/JSONObject.java intorno alla riga 2656, che l’issue identifica come percorso di serializzazione. Esegui la riproduzione TestEnumToString fornita e verifica come vengono convertiti i campi enum. Il lavoro è completato quando JSONObject.toString() rispetta una rappresentazione stringa sovrascritta dell’enum e la riproduzione produce i valori attesi.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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

Lingua principale
Java
Stelle
4.7k
Fork
2.6k
Merge medio
6g 20h
PR unite (30g)
2

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di stleary/JSON-java

Tutte le issue di stleary/JSON-java

Issue simili

Altre issue su Java

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.