Parsing JSON in Java con Jackson
Jackson è una delle varie librerie con cui eseguire il parsing del JSON con Java.
Nel mio caso l'ho dovuta usare per eseguire il parsing senza sapere a priori la struttura del JSON (quindi senza sapere quanti campi per record, e di che tipo sono).
Diamo a Cesare quel che è di Cesare, e quindi vi link la discussione sul forum HTML.it.
In sostanza, come potete leggere nella discussione, Jackson offre 3 modalità di parsing:
- la Streaming API, a basso livello. Ovvero estrai tu i "token" uno dopo l'altro e devi dedurre tu se si tratta di un campo String, un numero, l'inizio di un array, ecc
- Il Tree Model, ovvero Jackson ti fornisce una rappresentazione ad "albero" in memoria di tutto il JSON e puoi "navigarci" dentro tu come vuoi
- Il Data Binding che permette la mappatura tra il JSON e classi Java "bean".
A me serve la prima modalità.
Vi posto l'esempio che è uscito alla fine della discussione:
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.File;
import java.io.IOException;
public class TabellaJson {
private JsonFactory factory;
private JsonParser parser;
public TabellaJson(String json) throws IOException {
factory = new JsonFactory();
parser = factory.createParser(new File(json));
}
public void close() throws IOException {
parser.close();
}
public void parse() throws IOException {
JsonToken token;
while ((token = parser.nextToken()) != null) {
if (token == JsonToken.START_ARRAY) {
parseMainArray();
} else {
throw new IllegalStateException("Non è un array come previsto!");
}
}
}
private void parseMainArray() throws IOException {
JsonToken token;
while ((token = parser.nextToken()) != JsonToken.END_ARRAY) {
if (token == JsonToken.START_OBJECT) {
parseMainObject();
} else {
throw new IllegalStateException("Non è un oggetto come previsto");
}
}
}
private void parseMainObject() throws IOException {
System.out.println("--------------------------------");
JsonToken token;
while ((token = parser.nextToken()) != JsonToken.END_OBJECT) {
String fieldName = parser.getText();
token = parser.nextToken();
switch (token) {
case VALUE_STRING:
System.out.printf("%s = %s (String)%n", fieldName, parser.getValueAsString());
break;
case VALUE_NUMBER_INT:
System.out.printf("%s = %d (int)%n", fieldName, parser.getValueAsInt());
break;
case VALUE_NULL:
System.out.printf("%s = %s (String)%n", fieldName, "null");
break;
default:
throw new IllegalStateException("Tipo non specificato!");
}
}
}
}
A questo punto richiamiamo il tutto così:
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String filePath = "/home/matte/Desktop/clienti.json";
try {
TabellaJson lettura = new TabellaJson(filePath);
try {
lettura.parse();
} finally {
lettura.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Come vedete non sappiamo nulla di quali e quanti campi abbiamo; sappiamo solo che i vari JSON che dovrei "parsare" hanno una struttura di base simile (cominciano con un array, e poi ci sono tanti oggetti di non si sa quali e quanti campi).
Se usate Maven, potete installare la libreria così:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.9</version>
</dependency>
Rispetto ad altre librerie, la Straeming API è un pò più complicata da usare.
Però è anche molto più flessibile.
Enjoy!
java jackson json
Commentami!