Android 编程下使用 Google 的 Gson 解析 Json
Gson 相关 jar 包
下载地址:http://code.google.com/p/google-gson/
Gson 使用示例
package cn.sunzn.gson; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.util.Log; import cn.sunzn.bean.Person; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class GsonActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gson gson = new Gson(); /** * 将给定的 JSON 字符串转换成指定的类型对象 */ String json = "{\"name\":\"Tom\",\"age\":90}"; Person person = gson.fromJson(json, Person.class); Log.e("GSON", person.toString()); /** * 将给定的目标对象转换成 JSON 格式的字符串 */ String json_Person = gson.toJson(person); Log.e("GSON", json_Person); /** * 将给定的集合对象转换成 JSON 格式的字符串 */ ArrayList<Person> persons = new ArrayList<Person>(); Collections.addAll(persons, new Person("tom", 10), new Person("jon", 20)); String json_list = gson.toJson(persons); Log.e("GSON", json_list); /** * 将给定的 JSON 格式字符串转换为带泛型的集合对象 */ List<Person> retList = gson.fromJson(json_list, new TypeToken<List<Person>>() {}.getType()); for (Person p : retList) { Log.e("GSON", p.toString()); } } }
Gson 解析 Json 运行结果
02-19 07:39:23.467: E/GSON(669): Person [name=Tom, age=90]
02-19 07:39:23.487: E/GSON(669): {"name":"Tom","age":90}
02-19 07:39:23.517: E/GSON(669): [{"name":"tom","age":10},{"name":"jon","age":20}]
02-19 07:39:23.547: E/GSON(669): Person [name=tom, age=10]
02-19 07:39:23.547: E/GSON(669): Person [name=jon, age=20]
Gson 转换过程中使用的实体类 Person
package cn.sunzn.bean; import com.google.gson.annotations.Expose; public class Person { @Expose private String name; @Expose private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
Gson 演示源码下载:Gson
posted on 2013-12-25 10:59 clarenceV1 阅读(222) 评论(0) 编辑 收藏 举报