Java中List集合和JSON对象之间的相互转换

爱被打了一巴掌 2022-05-16 11:29 324阅读 0赞

第一种方法:

代码实现

  1. /**
  2. *数据封装成json
  3. *
  4. * @param items 物料入库数据
  5. * @return json
  6. * @throws JSONException
  7. */
  8. public static String GoodIn2Json(List<GoodInfo> items) throws JSONException {
  9. if (items == null) return "";
  10. JSONArray array = new JSONArray();
  11. JSONObject jsonObject = null;
  12. GoodInfo info = null;
  13. for (int i = 0; i < items.size(); i++) {
  14. info = items.get(i);
  15. jsonObject = new JSONObject();
  16. jsonObject.put(Api.COLORID, info.getColorId());
  17. jsonObject.put(Api.STOCK, info.getStock());
  18. array.put(jsonObject);
  19. }
  20. return array.toString();
  21. }
  22. /**
  23. * 将json数组解析出来,生成自定义数据的数组
  24. * @param data 包含用户自定义数据的json
  25. * @return 自定义信息的数据
  26. * @throws JSONException
  27. */
  28. public static List<MoreInfo> Json2UserDefine(String data) throws JSONException {
  29. List<MoreInfo> items = new ArrayList<>();
  30. if (data.equals("")) return items;
  31. JSONArray array = new JSONArray(data);
  32. JSONObject object = null;
  33. MoreInfo item = null;
  34. for (int i = 0; i < array.length(); i++) {
  35. object = array.getJSONObject(i);
  36. String key = object.getString(Api.KEY);
  37. String value = object.getString(Api.VALUE);
  38. item = new MoreInfo(key, value);
  39. items.add(item);
  40. }
  41. return items;
  42. }

第二种方法:

导入谷歌的Gson.jar

  1. //list转换为json
  2. Gson gson = new Gson();
  3. List<Person> persons = new ArrayList<Person>();
  4. String str = gson.toJson(persons);
  5. //json转换为list
  6. Gson gson = new Gson();
  7. List<Person> persons = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());

第三种方法:

导入阿里的fastJson.jar

  1. //list转换为json
  2. List<CustPhone> list = new ArrayList<CustPhone>();
  3. String str=JSON.toJSON(list).toString();
  4. //json转换为list
  5. List<Person> list = new ArrayList<Person>();
  6. list = JSONObject.parseArray(jasonArray, Person.class);

完!!!

发表评论

表情:
评论列表 (有 0 条评论,324人围观)

还没有评论,来说两句吧...

相关阅读