- 引入Gson库
implementation 'com.google.code.gson:gson:2.8.6'
- 准备json字符串
{"name":"怪盗kidou","age":24,"emailAddress":"ikidou@example.com"}
- 手敲一个TestBean.java,先不用GsonFormat插件。
public class TestBean {
public String name;
public String age;
public String emailAddress;
}
- 把json字符串转为java Bean对象。
public class MainActivity extends AppCompatActivity {
private static final String TAG = "xx";
String jsonStr = "{\"name\":\"怪盗kidou\",\"age\":24,\"emailAddress\":\"ikidou@example.com\"}";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestBean bean = new Gson().fromJson(jsonStr, TestBean.class);
Log.i(TAG, bean.name + " " + bean.age + " " + bean.emailAddress);
}
}
运行结果: