先放上一段JSON代码实例
[{"id":"5","version":"5.5","name":"Clash of Clans"},
{"id":"6","version":7.0","name":"Boom Beach"},
{"id":"7","version":3.5","name":"Clash Royale"}]
本文所载有两种方法对此JSON文件进行解析
一、为JSONObject
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest=(Button) findViewById(R.id.send_request);
responseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v){
if(v.getId()==R.id.send_request){
Log.d("1212121","121212121212");
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp(){
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpsURLConnection connection=null;
BufferedReader reader=null;
try{
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("http://10.0.2.2/get_data.json")
.build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
// parseJSONWithJSONObject(responseData);这种为JSONOject方法解析
parseJSONWithJSONObject1(responseData);这种为GSON方法解析
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithJSONObject1(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 is "+app.getId());
Log.d("MainActivtiy","name is "+app.getName());
Log.d("MainActivity","version is "+app.getVersion());
}
}
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 is"+id);
Log.d("MainActivity","name is"+name);
Log.d("MainActivity","name is"+version);
}
}catch(Exception e){
e.printStackTrace();
}
}
另外需注意在使用GSON方法需添加GSON库依赖和相应类的编写。本例代码如下:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.google.code.gson:gson:2.7'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
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;
}
}