Gson使用方法 GSON这个Java类库可以把Java对象转换成JSON(序列化),也可以把JSON字符串转换成一个相等的Java对象(反序列化)
1依赖 compile 'com.google.code.gson:gson:2.3.1'
2 toJason()方法将对象转换成Json字符串
class Person {
String name = "Li Lei"
int id = 1002;
}
Gson gson = new Gson();
Person person = new Person();
String str = gson.toJson(person);
3 fromJson()方法来实现从Json字符串转化为到java对象
Gson gson = new Gson();
Person person= gson.fromJson(str,Person.class);
class Person{
String name="Li Lei";
int id=1021;
}
public class AsyncHttp extends Activity
{
String str;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void toJson(View view) {
Person person=new Person();
Gson gson=new Gson();
str = gson.toJson(person);
Toast.makeText(AsyncHttp.this, str, Toast.LENGTH_SHORT).show();
}
public void fromJson(View view) {
Gson gson = new Gson();
Person person= gson.fromJson(str,Person.class);
Toast.makeText(AsyncHttp.this, person.name+ person.id, Toast.LENGTH_SHORT).show();
}
}
Gson的简单使用方法
最新推荐文章于 2024-07-10 19:36:21 发布