Problemi con GSON la serializzazione di un ArrayList di POJO di
-
25-10-2019 - |
Domanda
I era stato pensando di usare SimpleXML per le mie esigenze di serializzazione, ma pensato vorrei provare JSON fuori, per imparare qualcosa di nuovo.
Questo è il codice che sto usando per cercare di serializzare un ArrayList di prova POJO di utilizzare GSON 1.7.1.
Nota:. Ho rimosso il Reader / Scrittori per una stringa "s" per semplificare il codice
package test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.gson.Gson;
public class TestGsonSerialDeserialList {
public static void main(String[] args) throws IOException{
Gson gson = new Gson();
//Make Serial
String s;
List<TestObject> list = Collections.synchronizedList(new ArrayList<TestObject>() );
list.add(new TestObject());
list.add(new TestObject());
s = gson.toJson(list, ArrayList.class);
System.out.println(s);
//Eat Serial
List<TestObject> list2 = Collections.synchronizedList(gson.fromJson(s, ArrayList.class) );
System.out.println(list2.get(0) );
System.out.println(list2.get(1) );
}
}
Ecco l'uscita ottengo:
[{"objectID":1,"i1":12345,"name":"abcdefg","s":["a","b","c"]},{"objectID":2,"i1":12345,"name":"abcdefg","s":["a","b","c"]}]
java.lang.Object@5c74c3aa
java.lang.Object@75d9fd51
Ai miei occhi newbie questo sembra corretto. Solo, l'elenco degli oggetti deserializzato contiene oggetti di base, piuttosto che del TestObject I serializzato. Qualcuno può spiegare a me che cosa, se non altro, che posso fare per fare questo lavoro?
Modifica
Corretto a prova: Grazie a Colind
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class TestGsonSerialDeserialList {
public static void main(String[] args) throws IOException{
System.out.println("--- Serialize / Deserialize Started ---");
String fileName = "json\\testList.json";
Gson gson = new Gson();
Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType();
//Make Serial
Writer osWriter = new OutputStreamWriter( new FileOutputStream(fileName));
List<TestObject> list = Collections.synchronizedList(new ArrayList<TestObject>() );
list.add(new TestObject());
list.add(new TestObject());
list.add(new TestObject());
list.add(new TestObject());
gson.toJson(list, osWriter);
osWriter.close();
//Eat Serial
Reader isReader = new InputStreamReader( new FileInputStream((fileName) ) );
List<TestObject> list2 = Collections.synchronizedList(
(List<TestObject>)gson.fromJson(isReader, listOfTestObject)
);
isReader.close();
System.out.println(list2.get(0) );
System.out.println(list2.get(1) );
System.out.println(list2.get(2) );
System.out.println(list2.get(3) );
System.out.println("--- Serialize / Deserialize Ended ---");
}
}
uscita:
--- Serialize / Deserialize Started ---
ID#: 1, i1: 12345, name: abcdefg, s[]: [Ljava.lang.String;@95c083
ID#: 2, i1: 12345, name: abcdefg, s[]: [Ljava.lang.String;@6791d8c1
ID#: 3, i1: 12345, name: abcdefg, s[]: [Ljava.lang.String;@182d9c06
ID#: 4, i1: 12345, name: abcdefg, s[]: [Ljava.lang.String;@5a5e5a50
--- Serialize / Deserialize Ended ---
EDIT2:
Onestamente non so perché, ma quando ho sostituito il semplice String [] incorporato nel mio TestObject con un ArrayList, ha iniziato la serializzazione in modo corretto.
--- Serialize / Deserialize Started ---
ID#: 1, i1: 12345, name: abcdefg, s[]: [a, b, c]
ID#: 2, i1: 12345, name: abcdefg, s[]: [a, b, c]
ID#: 3, i1: 12345, name: abcdefg, s[]: [a, b, c]
ID#: 4, i1: 12345, name: abcdefg, s[]: [a, b, c]
--- Serialize / Deserialize Ended ---
Soluzione
È necessario fornire informazioni GSON sul tipo specifico generico di List
si sta utilizzando (o qualsiasi tipo generico si utilizza con esso). In particolare quando la deserializzazione JSON, è necessario che le informazioni per essere in grado di determinare quale tipo di oggetto dovrebbe deserializzare ciascun elemento di matrice a.
Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType();
String s = gson.toJson(list, listOfTestObject);
List<TestObject> list2 = gson.fromJson(s, listOfTestObject);
Questo è documentato nella href="https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples" rel="noreferrer"> manuale d'uso .