First, you need to build an entity class Person.java to correspond to the JSON
1 Public classPerson {2 PrivateString name;3 Private intAge ;4 PrivateString City;5 6 PublicPerson (String name,intAge , String city) {7 This. Name =name;8 This. Age =Age ;9 This. City =City ;Ten } One A PublicPerson () {} - - Public voidsetName (String name) { the This. Name =name; - } - - PublicString GetName () { + returnname; - } + A Public voidSetage (intAge ) { at This. Age =Age ; - } - - Public intGetage () { - returnAge ; - } in - Public voidsetcity (String city) { to This. City =City ; + } - the PublicString getcity () { * returnCity ; $ }Panax Notoginseng}
And then this is the specific implementation of encoding and decoding
1 Importandroid.support.v7.app.AppCompatActivity;2 ImportAndroid.os.Bundle;3 ImportAndroid.util.Log;4 5 ImportCom.google.gson.Gson;6 ImportCom.google.gson.reflect.TypeToken;7 8 ImportJava.lang.reflect.Type;9 Importjava.util.ArrayList;Ten Importjava.util.LinkedList; One Importjava.util.List; A - Public classMainactivityextendsappcompatactivity { - the @Override - protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); + -list<person> list =NewArraylist<person>(); +Person person =NewPerson ("Thh", "Chengdu"); A List.add (person); atperson =NewPerson ("CBB", "Chengdu"); - List.add (person); -person =NewPerson ("CMT", "Tianjin"); - List.add (person); - -Gson Gson =NewGson (); in -LOG.E ("ABC", "" "+Gson.tojson (list)); to +Person Person1 =NewPerson (); -Gson Gson1 =NewGson (); the *String s=Gson.tojson (list); $Type lt=NewTypetoken<list<person>> () {}.gettype ();//gets the data type of a generic typePanax NotoginsengList<person> l=Gson1.fromjson (S,LT); - for(person p1:l) { theLOG.E ("ABC", P1.getname () + "" "+ p1.getage () +" "+p1.getcity ()); + } A } the}
Results shown in Logcat:
10-22 01:22:01.444 16669-16669/? E/ABC: [{"Age": +, "City": "Chengdu", "Name": "Thh"},{"age": +, "City": "Chengdu", "Name": "CBB"},{"Age": "The City": " Tianjin "," name ":" CMT "}]10-22 01:22:01.448 16669-16669/? E/abc:thh chengdu10-22 01:22:01.448 16669-16669/? E/ABC:CBB chengdu10-22 01:22:01.449 16669-16669/? E/ABC:CMT Tianjin
Application of Gson in Android