JSON数据解析方法主要有:
JSONObject GSON Jackson FastJSON 前两种方法用的最多
JSONObject
//json数据 [{"number":"1","name":"one"},{"number":"2","name":"two"}] try { JSONArray jsonArray = new JSONArray("jsonData");// for(int i = 0;i<jsonArray.length();i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); String str = jsonObject.getString("number"); } } catch (JSONException e) { e.printStackTrace(); }
GSON
json数据:
build.gradle 中添加
compile 'com.google.code.gson:gson:2.8.0'
自定义一个GSONSimple类
public class GSONSimple { private String name; private String number; private String height; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } }
解析
Gson gson = new Gson(); List<GSONSimple> gsonList = gson.fromJson("jsonData",new TypeToken<List<GSONSimple>>(){}.getType()); for(GSONSimple gsonSimple:gsonList){ String number = gsonSimple.getNumber(); String name = gsonSimple.getName(); String height = gsonSimple.getHeight(); }
一会再写其余两个...