La estructura de almacenamiento del mapa es la forma clave/valor. La clave y el valor pueden ser de tipos ordinarios, o javabeans escritos por ellos mismos (este artículo), o lista con genéricos.
(Página del proyecto Github de GSON: https://github.com/google/gson)
Javabeo
En este ejemplo, debe centrarse en cómo convertir JSON a la definición de TypeToken cuando es un objeto Javabean normal.
Clase de entidad:
Punto de clase pública {private int x; privado int y; PUNTO PUBLIC (int x, int y) {this.x = x; this.y = y; } public int getx () {return x; } public void setX (int x) {this.x = x; } public int gety () {return y; } public void sety (int y) {this.y = y; } @Override public String toString () {return "punto [x =" + x + ", y =" + y + "]"; }}Clase de prueba:
import java.util.linkedhashmap; import java.util.map; import com.google.gson.gson; import com.google.gson.gsonbuilder; import com.google.gson.reflect.typetoken; Clase pública GSONTEST3 {public static void main (String [] args) {gson gson = new GsonBuilder (). EnableCompleMapKeySerialization () .Create (); MAP <Point, String> MAP1 = new LinkedHashMap <Point, String> (); // Use LinkedHashMap para ordenar los resultados en el orden de primera salida MAP1.put (nuevo punto (5, 6), "A"); map1.put (nuevo punto (8, 8), "b"); Cadena s = gson.tojson (map1); System.out.println (s); // resultado: [[{"x": 5, "y": 6}, "a"], [{"x": 8, "y": 8}, "b"]] map <punto, string> retMap = gson.fromjson (s, new Tystekoken <map <puntos, string> () {} .gettype ()); para (punto p: retmap.KeySet ()) {System.out.println ("Key:" + P + "Valores:" + retMap.get (p)); } System.out.println (retMap); System.out.println ("----------------------------------"); MAP <String, Point> MAP2 = new LinkedHashMap <String, Point> (); map2.put ("A", nuevo punto (3, 4)); map2.put ("b", nuevo punto (5, 6)); Cadena s2 = gson.tojson (map2); System.out.println (S2); MAP <String, Point> RetMap2 = Gson.FromJson (S2, new TypeToken <Map <String, Point >> () {} .GetType ()); for (clave de cadena: retmap2.keySet ()) {System.out.println ("Key:" + Key + "Valores:" + retMap2.get (key)); }}}resultado:
[[{"x": 5, "y": 6}, "a"], [{"x": 8, "y": 8}, "b"]] clave: punto [x = 5, y = 6] valores: una tecla: punto [x = 8, y = 8] Valores: b {punto [x = 5, y = 6] = a, punto [x = 8, y = 8] = b}---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- {"A": {"x": 3, "y": 4}, "b": {"x": 5, "y": 6}} clave: a valores: punto [x = 3, y = 4] clave: b valores: punto [x = 5, y = 6]Lista genérica
Clase de entidad:
import java.util.date; Estudiante de clase pública {private int id; nombre de cadena privada; cumpleaños de cita privada; public int getId () {return id; } public void setid (int id) {this.id = id; } public String getName () {nombre de retorno; } public void setName (nombre de cadena) {this.name = name; } Fecha pública GetBirthday () {regreso de cumpleaños; } public void setBirthday (cumpleaños de fecha) {this.birthday = cumpleaños; } @Override public string toString () {return "student [birthdle =" + birthdle + ", id =" + id + ", name =" + name + "]"; }} maestro de clase pública {private int id; nombre de cadena privada; título de cadena privada; public int getId () {return id; } public void setid (int id) {this.id = id; } public String getName () {nombre de retorno; } public void setName (nombre de cadena) {this.name = name; } public String gettitle () {Título de retorno; } public void settitle (título de cadena) {this.title = title; } @Override public string toString () {return "maestro [id =" + id + ", name =" + name + ",]"; }}Clase de prueba:
paquete com.tgb.lk.demo.gson.test4; import java.util.arrayList; import java.util.date; import java.util.linkedhashmap; import java.util.list; import java.util.map; import com.google.gson.gson; import com.google.gson.reflect.typetoken; clase pública GSONTEST4 {public static void main (String [] args) {Student Student1 = new Student (); estudiante1.setid (1); Student1.setName ("Li Kun"); Student1.setBirthday (nueva fecha ()); student2 = new Student (); estudiante2.setid (2); Student2.SetName ("Cao Guisheng"); Student2.SetBirthday (nueva fecha ()); Estudiante estudiante3 = nuevo estudiante (); estudiante3.setid (3); student3.setName ("liu bo"); estudiante3.setbirthday (nueva fecha ()); List <druent> stulist = new ArrayList <Enstude> (); stulist.add (Student1); stulist.add (Student2); stulist.add (Student3); Profesor profesor1 = nuevo maestro (); maestro1.setid (1); maestro1.setName ("maestro mi"); maestro1.settitle ("profesor"); Profesor profesor2 = nuevo maestro (); profesor2.setid (2); profesor2.setName ("maestro ding"); profesor2.settitle ("profesor"); Lista <firector> profesorList = new ArrayList <Cermema> (); profesorList.add (maestro1); profesorList.add (profesor2); Map <string, object> map = new LinkedHashMap <String, Object> (); map.put ("Estudiantes", estulista); MAP.put ("Teachers", MaestroList); Gson gson = new Gson (); Cadena s = gson.tojson (mapa); System.out.println (s); System.out.println ("----------------------------------"); MAP <String, Object> RetMap = Gson.FromJson (s, nuevo typetoken <map <string, list <ject>> () {} .gettype ()); for (clave de cadena: retmap.KeySet ()) {System.out.println ("Key:" + Key + "Valores:" + retMap.get (key)); if (key.equals ("Students")) {List <Sentuent> stulist = (list <diesta>) retMap.get (key); System.out.println (estulista); } else if (key.equals ("maestros")) {list <firector> tchrlist = (list <firector>) retMap.get (key); System.out.println (tchrlist); }}}}Resultado de salida:
{"students":[{"id":1,"name":"Li Kun","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":2,"name":"Cao Guisheng","birthDay":"Jun 22, 2012 9:48:19 PM"},{"id":3,"name":"Liu Bo","birthDay":"Jun 22, 2012 9:48:19 pm "}]," maestros ": [{" id ": 1," nombre ":" maestro mi "," título ":" profesor "}, {" id ": 2," nombre ":" maestro ding "," título ":" profesor "}}}} --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- birthDay=Jun 22, 2012 9:48:19 PM}, {id=3.0, name=Liu Bo, birthDay=Jun 22, 2012 9:48:19 PM}] key:teachers values:[{id=1.0, name=Teacher Mi, title=Professor}, {id=2.0, name=Teacher Ding, title=Lecturer}] [{id=1.0, name=Teacher Mi, title=Professor}, {id = 2.0, name = maestro ding, title = Lecturer}]