JSON 数据解析
JSONObject 解析json数据
//JSONObject 解析json数据
private void parseJsonWithJSONObject(String jsonData) {
try {
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 version = jsonObject.getString("version");
Log.d("MainActivity", "id :"+id+"\t\tname :"+name+"\t\tversion:"+version);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Gson 解析json数据
参考 https://github.com/EmotionalRonanyg/gson
依赖 compile ‘com.google.code.gson:gson:2.8.0’
//Gson 解析json数据
private void parseJsonWithGson(String jsonData) {
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
for (App app:appList){
Log.d("MainActivity---","id:"+app.getId()+"\t\tname:"+app.getName()+"\t\tversion: "+app.getVersion());
}
}
Http请求
参考 https://github.com/EmotionalRonanyg/okhttp
OkHttp 依赖 compile ‘com.squareup.okhttp3:okhttp:3.7.0’
private void sendRequestWithOkHttp() {
//开启线程 发送网络请求
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//json数据
.url("http://emotionalronanyg.github.io/get_data.json")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
//JSONObject 解析json
parseJsonWithJSONObject(responseData);
//Gson 解析json
parseJsonWithGson(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();//开启线程
}
APP 实体
public class App {
private String id;
private String name;
private String version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}