A estrutura de armazenamento do mapa é o formulário de chave/valor. A chave e o valor podem ser de tipos comuns, ou Javabeans escritos por eles mesmos (este artigo) ou listar com genéricos.
(Página do projeto do Github do GSON: https://github.com/google/gson)
Javabean
Neste exemplo, você deseja se concentrar em como converter o JSON de volta à definição de TypeToken quando um objeto Javabean normal.
Classe de entidade:
public class Point {private Int X; private int y; public Point (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 "Point [x =" + x + ", y =" + y + "]"; }}Classe de teste:
importar java.util.linkedhashmap; importar java.util.map; importar com.google.gson.gson; importar com.google.gson.gsonbuilder; importar com.google.gson.reflect.typetken; classe pública gsontest3 {public static void main (string [] args) {gson gson = new gsonbuilder (). enableComplexMapkeySerialization () .create (); Mapa <ponto, string> map1 = new LinkedHashMap <Point, String> (); // Use LinkedHashMap para classificar os resultados no primeiro pedido de ordem map1.put (new Point (5, 6), "A"); map1.put (novo ponto (8, 8), "b"); String s = gson.tojson (map1); System.out.println (s); // Resultado: [[{"x": 5, "y": 6}, "a"], [{"x": 8, "y": 8}, "b"]] map <Point, string> retmap = gson.fromjson (sget typeteken <ppoint, string> (string> (string> Retmap = gson.fromjson (sget, typeToken <ppoint, string> for (ponto P: retmap.keyset ()) {System.out.println ("chave:" + p + "valores:" + retmap.get (p)); } System.out.println (retmap); System.out.println ("--------------------------------"); Mapa <string, ponto> map2 = new LinkedHashmap <string, ponto> (); map2.put ("A", New Point (3, 4)); map2.put ("b", novo ponto (5, 6)); String s2 = gson.tojson (map2); System.out.println (S2); Mapa <string, ponto> retmap2 = gson.fromjson (s2, novo typeToken <map <string, ponto >> () {} .gettype ()); para (chave de string: retmap2.keyset ()) {System.out.println ("Key:" + Key + "valores:" + retmap2.get (key)); }}}resultado:
[[[{"x": 5, "y": 6}, "a"], [{"x": 8, "y": 8}, "b"]] chave: ponto [x = 5, y = 6] {"A": {"x": 3, "y": 4}, "b": {"x": 5, "y": 6}}}}} Tecla: a valores: ponto [x = 3, y = 4] Chave: B Valores: Point [x = 5, y = 6]Lista genérica
Classe de entidade:
importar java.util.date; Public Class Student {private Int ID; nome de string privado; aniversário privado; public int getId () {return id; } public void setId (int id) {this.id = id; } public string getName () {return name; } public void setName (nome da string) {this.name = name; } public data getBirthday () {return Birthday; } public void setbirthday (data de aniversário) {this.birthday = aniversário; } @Override public string tostring () {return "Student [aniversário =" + aniversário + ", id =" + id + ", name =" + name + "]"; }} Professor de classe pública {private int id; nome de string privado; título de sequência privada; public int getId () {return id; } public void setId (int id) {this.id = id; } public string getName () {return name; } public void setName (nome da string) {this.name = name; } public string gettitle () {return título; } public void Settitle (título da string) {this.title = title; } @Override public string tostring () {return "professor [id =" + id + ", name =" + name + ",]"; }}Classe de teste:
pacote com.tgb.lk.demo.gson.test4; importar java.util.arraylist; importar java.util.date; importar java.util.linkedhashmap; importar java.util.list; importar java.util.map; importar com.google.gson.gson; importar com.google.gson.reflect.typetken; classe pública gsontest4 {public static void main (string [] args) {Student Student1 = new Student (); estudante1.setId (1); Student1.setName ("Li Kun"); estudante1.setBirthday (new Date ()); estudante2 = novo aluno (); estudante2.setId (2); Student2.SetName ("Cao Guisheng"); Student2.SetBirthday (new Date ()); Aluno estudante3 = novo aluno (); Student3.SetId (3); Student3.SetName ("Liu Bo"); estudante3.setBirthday (new Date ()); List <very Student> estulista = new ArrayList <very Student> (); estulista.add (Student1); estulista.Add (Student2); estulista.add (Student3); Professor1 = novo professor (); professor1.setId (1); Professor1.setName ("Professor MI"); Professor1.Settitle ("Professor"); Professor2 = novo professor (); professor2.setId (2); professor2.setName ("Professor Ding"); Professor2.Settitle ("Professor"); Lista <PRESSIGN> professorlist = new ArrayList <PRESSION> (); professorlist.add (Professor1); professorlist.add (Professor2); Mapa <string, objeto> map = new LinkedHashMap <string, object> (); map.put ("alunos", estulista); map.put ("Professores", Lista de Professores); Gson gson = new gson (); String s = gson.tojson (mapa); System.out.println (s); System.out.println ("--------------------------------"); Mapa <string, objeto> retmap = gson.fromjson (s, novo typeToken <map <string, list <ject>>> () {} .gettype ()); para (chave de string: retmap.keyset ()) {System.out.println ("Key:" + Key + "valores:" + retmap.get (key)); if (key.equals ("estudantes")) {list <verydge> estulist = (list <ver -se>) retmap.get (key); System.out.println (estulista); } else if (key.equals ("Professores")) {list <festrower> tchrlist = (list <fora>) retmap.get (key); System.out.println (tchrlist); }}}}Resultado da saída:
{"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 21:48:19 "}]," Professores ": [{" id ": 1," Nome ":" Professor Mi "," Title ":" Professor "}, {" Id ": 2," Name ":" Professor Ding "," Title ":" Lecturer "}]}} ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- aniversário = 22 de junho de 2012 21:48:19 pm}, {id = 3.0, nome = liu bo, aniversário = 22 de junho de 2012 21:48:19 pm}] Chave: Professores Valores: [{id = 1.0, nome = professor Mi, title = Professor}, {Id = 2.0, Nome = Ding Ding, título = lecturer} {id = 2.0, nome = professor ding, title = palestrante}]