今天研究了下解析服务器上的json文件
先给大家看一下服务器上的json文件里面的内容
{"list":2,"persons":[{"pid":1,"pname":"傻逼","page":22},{"pid":2,"pname":"鬼子","page":22},{"pid":3,"pname":"傻逼2","page":22}]}
就是这么点数据,但是通过json解析,可以以对象的方式得到它
接下来就直接给大家看代码了
xml里面的代码其实也没什么,就是一个Button里面带有一个点击事件,那就直接上Java代码了
package com.liuqian.android_30parsejson; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import com.alibaba.fastjson.JSON; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void parserJson(View view){ //获取网络Json new MyTask().execute(); } class MyTask extends AsyncTask{ @Override protected Object doInBackground(Object[] params) { try { URL url=new URL(getString(R.string.server_name)+"persons.json"); HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); //设置请求方式 httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(5000); //获取结果码 int code=httpURLConnection.getResponseCode(); Log.i("test",code+""); if(code==200){//响应成功 InputStream is=httpURLConnection.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String str=null; StringBuffer stringBuffer=new StringBuffer(); while ((str=br.readLine())!=null){ stringBuffer.append(str); Log.i("test",stringBuffer.toString()); } //解析json /*//01开始使用原生态 JSONObject jsonObject=new JSONObject(stringBuffer.toString()); int list=jsonObject.getInt("list"); Log.i("test","长度"+list); JSONArray jsonArray=new JSONArray("persons"); for (int i = 0; i <jsonArray.length() ; i++) { JSONObject object=jsonArray.getJSONObject(i); int pid=object.getInt("pid"); String pname=object.getString("pname"); int page=object.getInt("page"); Log.i("test",pid+pname+page); }*/ //2.使用gson解析json /* Gson gson=new Gson(); BigPerson bigPerson=gson.fromJson(stringBuffer.toString(),BigPerson.class); Log.i("test",bigPerson.getList()+""); List<SmallPerson> persons=bigPerson.getPersons(); for (SmallPerson person:persons) { Log.i("test",person.toString()); }*/ //3.使用FastJson解析 BigPerson bigPerson= JSON.parseObject(stringBuffer.toString(),BigPerson.class); Log.i("test",bigPerson.getList()+""); List<SmallPerson> persons=bigPerson.getPersons(); for (SmallPerson person:persons) { Log.i("test",person.toString()); } } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); } } }
三种方法都在里面,但是还需要在manifest里面加一个网络的权限
而且需要注意的是,展示数据只能在OnPostExecute这个方法里面,因为存入数据的集合只有在此方法中才有效
今天本人的分享也就到这里了,如有失误,请指正,本人虚心接受,谢谢!!