导入gson.jar
bean:
public class Person {
private String name;
private int age;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return name + ":" + age;
}
}
Activity类
public class MainActivity extends Activity {
private Button json;
private Button gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
json = (Button) findViewById(R.id.json);
gson = (Button) findViewById(R.id.gson);
json.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 对象转json
Gson gson = new Gson();
List<Person> persons = new ArrayList<Person>();
for (int i = 0; i < 5; i++) {
Person p = new Person();
p.setName("name" + i);
p.setAge(i * 5);
persons.add(p);
}
String str = gson.toJson(persons);
Log.d(TAG, "json==>>>" + str);
}
});
gson.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// json转对象
Gson gson = new Gson();
String str = "[{\"name\":\"xiaoming\",\"age\":22},{\"name\":\"xiaowang\",\"age\":0}]";
List<Person> ps = gson.fromJson(str,
new TypeToken<List<Person>>() {
}.getType());
for (int i = 0; i < ps.size(); i++) {
Person p = ps.get(i);
Log.d(TAG, "gson==>>>" + p.toString());
}
//Person person = gson.fromJson(str, Person.class);
//Log.i(TAG, "gson==>>>" + person.toString());
}
});
}
}