json数据是我们比较常见的数据格式,多是从服务器返回的数据,而解析json的方式也有很多,这里主要记录使用Android官方的JSONObject和谷歌开源的GSON两种方式
一、layout布局
就放两个button好了
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_JSON"
android:text="JSONObject"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_GSON"
android:text="btn_GSON"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
二、Java代码
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_JSON,btn_GSON;
//先设置一个json字符串,可以是从服务器获取
private String json = "[{'id':'1','name':'name1','sex':'nan'},{'id':'2','name':'name2','sex':'nv'},{'id':'3','name':'name3','sex':'nan'}]";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_JSON = findViewById(R.id.btn_JSON);
btn_JSON.setOnClickListener(this);
btn_GSON = findViewById(R.id.btn_GSON);
btn_GSON.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_JSON:
parse_JOSNObject(json);//使用JOSNObject方式解析
break;
case R.id.btn_GSON:
parse_GSON(json);//使用GSON方式解析
break;
}
}
}
三、使用JSONObject解析
private void parse_JOSNObject(String jsonData){
try {
//如果得到的json不是数组,就不要用JSONArray,否则会报错
//直接用 JSONObject jsonObject = new JSONObject(jsonData);
JSONArray jsonArray = new JSONArray(jsonData);
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String sex = jsonObject.getString("sex");
Log.e("JSON", "parseJOSNObject: "+"id:"+id+",name:"+name+",sex:"+sex );
}
}catch (Exception e){e.printStackTrace();}
}
四、使用GSON解析
GSON的特点是可以将json数据映射到一个类,方便读取数据
1.在gradle添加GSON依赖
implementation 'com.google.code.gson:gson:2.8.6'
2.建立对应的类(Java Bean)
public class User {
private String id;
private String name;
private String sex;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
.......
}
3.使用GSON
private void parse_GSON(String jsonData){
Gson gson = new Gson();
List<User> userList = gson.fromJson(jsonData,new TypeToken<List<User>>(){}.getType());
for (User user:userList){
Log.e("parse_GSON", "id: "+user.getId()+",name:"+user.getName()+",sex:"+user.getSex() );
}
}
五、补充
使用Android Studio创建setter和getter的方法
菜单栏->Code->Generate->getter and setter
快捷键是Alt+Insert