接着使用google的开源库GSON来实现,用到开源库,那就先下载了。gson下载地址:GSON下载地址点击这里。gson gitbub地址:https://github.com/google/gson。
GSON库主要是将一段JSON格式的字符串自动映射成一个对象,从而不需要编写代码去解析。这里新建一个Person类来获取数据,代码如下:
MainActivity中添加代码: void parseJSONWithGSON(String jsonData) { Gson gson = new Gson(); List<Person> personList = gson.fromJson(jsonData, new TypeToken<List<Person>>(){}.getType()); for (Person person :personList) { Log.d(TAB, "Gson: name is: " + person.getName()); Log.d(TAB, "Gson: age is: " + person.getAge()); Log.d(TAB, "Gson: sex is:" + person.getSex()); } } void getJSONWithGSON(String url) { AsyncHttpClient client = new AsyncHttpClient(); client.get(url, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { try { String response = new String(bytes, 0, bytes.length, "utf-8"); parseJSONWithGSON(response); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { } }); }
这里new了一个Gson,然后通过fromJson的方法,通过TypeToken获取数据并保存到Person列表中。运行看下效果: 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: name is: xiao hong 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: age is: 25 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: sex is:wonan 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: name is: xiao ming 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: age is: 15 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: sex is:man 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: name is: xiao qiang 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: age is: 30 02-20 10:42:56.381 6434-6434/? D/JSONStudy: Gson: sex is:man 当然如果想要生存json数据,也是可以用gson的tojson方法的。