Operações de conversão comumente usadas para estruturas como LIST e MAP podem atender basicamente na maioria das necessidades que lidamos, mas às vezes existem regulamentos especiais de formato para o JSON no projeto. Por exemplo, o seguinte JSON String Parsing:
[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:54:49 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]
Após a análise, descobrimos que os métodos comuns não são fáceis de lidar com a string json acima. Por favor, veja como este artigo lida:
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 + ",]"; }}Observe que uma classe de entidade de TABLEATA é definida aqui:
importar java.util.list; classe pública Tabledata {private string tableName; Lista privada TABLEATA; public string gettableName () {return tableName; } public void SettableName (String tableName) {this.tablename = tableName; } public list gettabledata () {return tabledata; } public void SettableData (Lista TABLETATA) {this.tabledata = TABLEDATA; }} Classe de teste:
(Olhe cuidadosamente para a implementação da conversão de JSON de volta a um objeto. Após duas conversões aqui, o resultado da primeira retrocesso é que o mapa não é o objeto que esperamos. Depois de converter o mapa para JSON novamente, depois convertê -lo em um objeto. O que eu citei é que o jar de GSON2.1 é tratado normalmente.
importar java.util.arraylist; importar java.util.date; importar java.util.list; importar com.google.gson.gson; importar com.google.gson.reflect.typetken; classe pública gsontest5 { / ** * @param args * / public static void main (string [] args) {// converte o objeto para json-> iniciar o aluno do aluno1 = new Student (); estudante1.setId (1); Student1.setName ("Li Kun"); estudante1.setBirthday (new Date ()); Aluno aluno2 = 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); Tobledata td1 = new tabledata (); td1.settableName ("estudantes"); td1.settabledata (estulista); Tobledata td2 = new tabledata (); td2.SettableName ("Professores"); td2.settabledata (professor); Lista <Abledata> tdlist = new ArrayList <ArbleData> (); tdlist.add (td1); tdlist.add (td2); Gson gson = new gson (); String s = gson.tojson (tdlist); System.out.println (s); // Resultado: [{"TableName": "Students", "Tabledata": [{"ID": 1, "Nome": "Li Kun", "Aniversário": "Jun 22, 2012 10:44:16 AM"}, {"ID": 2, "Nome": "Cao Guisheng", "" ":" 22, 22, 2012 ": Sou "}, {" id ": 3," nome ":" liu bo "," aniversário ":" 22 de junho de 2012 10:44:16 "}, {" id ": 3," nome ":" liu bo "," aniversário ":" Jun 22, 2012 10:44:16 Am "}]}, {" TableName ":" Professores "," Tabledata ": [{" ID ": 1," Nome ":" Professor Mi "," Title ":" Professor "}, {" Id ": 2," Nome ":" Professor Ding "," Title ":" Lecturer "}}] // //////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////Iive de //////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////Iive de TypeToken <list <Tawledata >> () {} .gettype ()); for (int i = 0; i <taBledaTAs2.Size (); i ++) {Tawledata entityData = TABLEDATAS2.get (i); String tableName = entityData.gettableName (); Lista TABLEATA = entityData.gettabledata (); String s2 = gson.tojson (TABELATA); // System.out.println (S2); // System.out.println (entityData.getData ()); if (tableName.equals ("alunos")) {System.out.println ("alunos"); Lista <Dentro> retstulist = gson.Fromjson (S2, novo TypeToken <List <Ardent>> () {} .gettype ()); for (int j = 0; j <retStulist.size (); j ++) {System.out.println (retstulist.get (j)); }} else if (tableName.equals ("professores")) {System.out.println ("Professores"); Lista <PRESSIGN> Rettchrlist = GSON.Fromjson (S2, New TypeToken <List <Fester>> () {} .gettype ()); for (int j = 0; j <Rettchrlist.size (); j ++) {System.out.println (Rettchrlist.get (j)); }}} // json é convertido em um objeto -> end}}Resultado da saída:
[{"TableName": "Students", "Tawledata": [{"ID": 1, "Nome": "Li Kun", "Aniversário": "Jun 22, 2012 22:04:12"}, {"ID": 2, "Nome": "Cao Guisheng", "" Jun 22, "Id" 10:2 "12 ": Bo","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":3,"name":"Liu Bo","birthDay":"Jun 22, 2012 10:04:12 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"Teacher Mi "," title ":" Professor "}, {" id ": 2," nome ":" professor ding "," title ":" palestrante "}]}] estudante estudante [aniversário = fri jun 22 22:04:12 cst 2012, id = 1, name = li kun] estudante [FRI = FRI 22 22 22:04: 22:04:12 CST 2012, id = 3, nome = Liu Bo] Professor dos professores [id = 1, nome = professor MI, título = professor] professor [id = 2, nome = professor Ding, título = professor]Registre o TypeAdapter e o manuseio dos tipos de enum
Os tipos de enumeração trazem benefícios ao nosso programa. Como usar o GSON para alcançar o intercâmbio com o JSON? Por favor, veja este artigo.
Este artigo se concentra em como escrever um TypeAdapter, registrar o TypeAdapter e o manuseio dos tipos de enum.
Classe de entidade:
public Enum PackAGestate {play, atualize, atualizando, baixando, baixando,} public class PackageItem {private string Name; Estado de PackAgestate Private; Tamanho do String Private; public String getName () {Return Name; } public void setName (nome da string) {this.name = name; } public packAgestate getState () {retornar estado; } public void setState (PackAgestate State) {this.state = state; } public string getSize () {return size; } public void SetSize (tamanho da string) {this.size = size; } @Override public string tostring () {return "packageItem [name =" + name + ", size =" + size + ", state =" + state + "]"; }}Escreva um conversor você mesmo para implementar a interface jsonserializer <t> e interface JSondeSerializer <T>:
importar java.lang.reflect.type; importar com.google.gson.jSondSerializationContext; importar com.google.gson.jsondseserializer; importar com.google.gson.jsonElement; importar com.google.gson.jsonparseException; importar com.google.gson.jsonPrimitive; importar com.google.gson.jsonPrimitive; importar com.google.gson.jsonserializationContext; importar com.google.gson.jsonserializer; A classe pública enumeserializer implementa o JSOnserializer <CackAgestate>, JSondeSerializer <CackAgestate> {// chamado quando o objeto é convertido para JSON, implementando JSOnserializer <ctyAgestate> interface @Override JSoNelement Serialize (PackAgestate State, Type Arg1, JSOnserializerdConten. JsonPrimitive (state.ordinal ()); } // chamado quando o objeto é convertido em JSondeSerializer <ckegoState> interface @Override public PackAgestate Deserialize (JSonelement JSON, Type Typeoft, JSondSerializationContext context) lança () lompensexceptsception {if (json.getasInt () <cackAgestate.values (). retornar nulo; }}Classe de teste:
importar com.google.gson.gson; importar com.google.gson.gsonbuilder; classe pública gsontest6 {public static void main (string [] args) {gsonbuilder gsonbuilder = new gsonbuilder (); gsonbuilder.registertypeadapter (packAgestate.class, new enumserializer ()); Gson gson = gsonbuilder.create (); PackageItem item = new PackageItem (); item.setName ("item_name"); item.SetSize ("500m"); item.SetState (packAgestate.UpDating); // 这个 State 是枚举值 String s = gson.tojson (item); System.out.println (s); System.out.println ("------------------------------"); PackageItem retitem = gson.fromjson (s, packageItem.class); System.out.println (retitem); }}
Resultado da saída (o tipo de estado de enumeração correspondente foi convertido para o tipo int no resultado):
{"name": "item_name", "estado": 2, "size": "500m"} --------------------------------------- packageItem [nome = item_name, size = 500m, estado = atualização]