/** * 把集合转到json格式 * @param vipList * @return * @throws JSONException */ public static String parseListJson(List<VIP> vipList) throws JSONException { String json = ""; JSONArray array = new JSONArray(); for (VIP vip : vipList) { JSONObject object = new JSONObject(); object.put("id",vip.getId()); object.put("name",vip.getName()); object.put("score",vip.getScore()); object.put("phone",vip.getPhone()); array.put(object); } // json =array.toString(); json = com.alibaba.fastjson.JSON.toJSONString(vipList); Log.e("json",json); return json; }
[{"id":1,"name":"zhangsan","score":1000},{"id":2,"name":"zhangsan","score":1000},{"id":3,"name":"zhangsan","score":1000},{"id":4,"name":"zhangsan","score":1000},{"id":5,"name":"zhangsan","score":1000},{"id":6,"name":"zhangsan","score":1000},{"id":7,"name":"zhangsan","score":1000},{"id":8,"name":"zhangsan","score":1000},{"id":9,"name":"zhangsan","score":1000},{"id":10,"name":"zhangsan","score":1000}]
public static List<VIP> parseJson2(String jsonStr) { List<VIP> vipList = new ArrayList<>(); if (null != jsonStr && jsonStr.length() > 0) { try { JSONArray jsonArray = new JSONArray(jsonStr); if (jsonArray.length() > 0) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject valueJsonObject = new JSONObject(jsonArray.getString(i)); VIP vip = new VIP(); vip.setId(Integer.parseInt(valueJsonObject.getString("id"))); vip.setName(valueJsonObject.getString("name")); vip.setScore(Integer.parseInt(valueJsonObject.getString("score"))); // vip.setScore(Integer.parseInt(valueJsonObject.getString("phone"))); ; vipList.add(vip); } } } catch (JSONException e) { e.printStackTrace(); } } return vipList; }