首先需要建一个实体类 Person.java 来对应json
1 public class Person { 2 private String name; 3 private int age; 4 private String city; 5 6 public Person(String name, int age, String city){ 7 this.name = name; 8 this.age = age; 9 this.city = city; 10 } 11 12 public Person(){} 13 14 public void setName(String name) { 15 this.name = name; 16 } 17 18 public String getName() { 19 return name; 20 } 21 22 public void setAge(int age) { 23 this.age = age; 24 } 25 26 public int getAge() { 27 return age; 28 } 29 30 public void setCity(String city) { 31 this.city = city; 32 } 33 34 public String getCity() { 35 return city; 36 } 37 }
然后这是编码和解码的具体实现
1 import android.support.v7.app.AppCompatActivity; 2 import android.os.Bundle; 3 import android.util.Log; 4 5 import com.google.gson.Gson; 6 import com.google.gson.reflect.TypeToken; 7 8 import java.lang.reflect.Type; 9 import java.util.ArrayList; 10 import java.util.LinkedList; 11 import java.util.List; 12 13 public class MainActivity extends AppCompatActivity { 14 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_main); 19 20 List<Person> list = new ArrayList<Person>(); 21 Person person = new Person("Thh", 23, "CHENGDU"); 22 list.add(person); 23 person = new Person("CBB", 22, "CHENGDU"); 24 list.add(person); 25 person = new Person("CMT", 18, "TIANJIN"); 26 list.add(person); 27 28 Gson gson = new Gson(); 29 30 Log.e("ABC", "" + gson.toJson(list)); 31 32 Person person1 = new Person(); 33 Gson gson1 = new Gson(); 34 35 String s=gson.toJson(list); 36 Type lt=new TypeToken<List<Person>>(){}.getType();//获取一个泛型的数据类型 37 List<Person> l=gson1.fromJson(s,lt); 38 for(Person p1:l){ 39 Log.e("ABC",p1.getName() + " " + p1.getAge() + " " + p1.getCity()); 40 } 41 } 42 }
Logcat中显示结果:
10-22 01:22:01.444 16669-16669/? E/ABC: [{"age":23,"city":"CHENGDU","name":"Thh"},{"age":22,"city":"CHENGDU","name":"CBB"},{"age":18,"city":"TIANJIN","name":"CMT"}] 10-22 01:22:01.448 16669-16669/? E/ABC: Thh 23 CHENGDU 10-22 01:22:01.448 16669-16669/? E/ABC: CBB 22 CHENGDU 10-22 01:22:01.449 16669-16669/? E/ABC: CMT 18 TIANJIN
时间: 2024-10-06 18:24:25