什么是json?
json全称就是javaScript Object Notation,是一种轻量级的数据交换格式,以一种键值(key,value)的形式存在。那安卓上是怎么实现创建和读取的呢?下面来学习学习。
首先是创建json格式,一般我们都会用到JsonObeject这个类,创建其对象。
PRotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView= (TextView) findViewById(R.id.text1); try { JSONObject root = new JSONObject(); JSONObject jsonObject1 = new JSONObject(); JSONObject jsonObject2 = new JSONObject(); JSONArray jsonArray = new JSONArray(); //一个json对象 jsonObject1.put("name","xixi"); jsonObject1.put("age",18); jsonObject1.put("sex","male"); //第二个json对象 jsonObject2.put("name","haha"); jsonObject2.put("age",19); jsonObject2.put("sex","male"); //json数组 jsonArray.put(jsonObject1); jsonArray.put(jsonObject2); //将json数组添加到root这个jsonObject这个类的对象里去,并指定它的键为handsome root.put("handsome",jsonArray); System.out.println(root.toString()); } catch (JSONException e) { e.printStackTrace(); } }这样就创建了json格式,我们通过控制台看到打印的内容。
那如何通过网络读取json数据呢?我们贴上代码。
//在安卓3.0之后google要求网络请求要在子线程中进行 new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { try { //输入流,并指定其url地址,打开流 InputStream in = new URL("http://aqicn.org/publishingdata/json").openStream(); //通过BufferedReader来入去inputStream,其中inputStreamReader来封装inputStream BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; StringBuffer content = new StringBuffer(); while ((line = br.readLine()) != null) { content.append(line); } //读取完成之后关闭BufferedReader br.close(); return content.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } //当网络操作成功连接之后调用这个方法 @Override protected void onPostExecute(String s) { //s为从网络读取的数据 if (s!=null){ try { //创建一个数组对象,放入s内容 JSONArray jo= new JSONArray(s); JSONObject jso = jo.getJSONObject(0); //从网络中取到键为pollutants这个键然后读取其内容 JSONArray pollutants = jso.getJSONArray("pollutants"); //控制台输出 System.out.println("cityName: "+jso.getString("cityName")); } catch (JSONException e) { e.printStackTrace(); } } } }.execute();如图所示,我们已经顺利读取了网络的数据。
新闻热点
疑难解答