json与gson互转
json与gson互转
导入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());
}
});
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。