1. Introduzione
In questo tutorial, esamineremo un paio di approcci per l'iterazione su un JSONObject , una semplice rappresentazione JSON per Java.
Inizieremo con una soluzione ingenua e poi esamineremo qualcosa di un po 'più robusto.
2. Iterazione attraverso un JSONObject
Cominciamo con il semplice caso di iterare un JSON di coppie nome-valore:
{ "name": "Cake", "cakeId": "0001", "cakeShape": "Heart" }
Per questo, possiamo semplicemente iterare attraverso i tasti usando il metodo keys () :
void handleJSONObject(JSONObject jsonObject) { jsonObject.keys().forEachRemaining(key -> { Object value = jsonObject.get(key); logger.info("Key: {0}\tValue: {1}", key, value); } }
E il nostro output sarà:
Key: name Value: Cake Key: cakeId Value: 0001 Key: cakeShape Value: Heart
3. Attraversare un JSONObject
Ma diciamo che abbiamo una struttura più complessa:
{ "batters": [ { "type": "Regular", "id": "1001" }, { "type": "Chocolate", "id": "1002" }, { "type": "BlueBerry", "id": "1003" } ], "name": "Cake", "cakeId": "0001" }
Cosa significa in questo caso scorrere i tasti?
Diamo un'occhiata a ciò che il nostro approccio ingenuo keys () ci darebbe:
Key: batters Value: [{"type":"Regular","id":"1001"},{"type":"Chocolate","id":"1002"}, {"type":"BlueBerry","id":"1003"}] Key: name Value: Cake Key: cakeId Value: 0001
Questo, forse, non è altrettanto utile. Sembra che quello che vogliamo in questo caso non sia l'iterazione, ma invece l'attraversamento.
Attraversare un JSONObject è diverso dall'iterare un set di chiavi JSONObject .
Per questo, dobbiamo effettivamente controllare anche il tipo di valore. Immaginiamo di farlo in un metodo separato:
void handleValue(Object value) { if (value instanceof JSONObject) { handleJSONObject((JSONObject) value); } else if (value instanceof JSONArray) { handleJSONArray((JSONArray) value); } else { logger.info("Value: {0}", value); } }
Quindi, il nostro approccio è ancora abbastanza simile:
void handleJSONObject(JSONObject jsonObject) { jsonObject.keys().forEachRemaining(key -> { Object value = jsonObject.get(key); logger.info("Key: {0}", key); handleValue(value); }); }
L'unica cosa è che dobbiamo pensare a come gestire gli array.
4. Attraversare un JSONArray
Proviamo a mantenere un approccio simile all'utilizzo di un iteratore. Invece di chiamare keys () , chiameremo iterator () :
void handleJSONArray(JSONArray jsonArray) { jsonArray.iterator().forEachRemaining(element -> { handleValue(element) }); }
Ora, questa soluzione è limitante perché stiamo combinando l'attraversamento con l'azione che vogliamo intraprendere . Un approccio comune per separare i due sarebbe l'utilizzo del pattern Visitor.
5. conclusione
In questo articolo, abbiamo visto un modo per iterare su un JSONObject per semplici coppie nome-valore, il problema associato a strutture complesse e una tecnica di attraversamento per risolverlo.
Naturalmente, questo era un metodo di attraversamento prima in profondità, ma potevamo fare prima l'ampiezza in modo simile.
Il codice completo per l'esempio è disponibile su Github.