Java tutorial
/** * RSSin - Clever RSS reader for Android * Copyright (C) 2015 Randy Wanga, Jos Craaijo, Joep Bernards, Camil Staps * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.rssin.serialization; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * Common tools for JSON serialization * @author */ public class JsonSerializer { /** * Make a JSONArray from a List<? extends Jsonable> * @param list the list to serialize * @return the JSONArray * @throws JSONException if this happens, it should be a problem in the Jsonable's toJson */ public static JSONArray listToJson(List<? extends Jsonable> list) throws JSONException { JSONArray json = new JSONArray(); for (Jsonable item : list) { json.put(item.toJson()); } return json; } public static JSONArray numbersListToJson(List<? extends Number> list) throws JSONException { JSONArray json = new JSONArray(); for (Number item : list) { json.put(item); } return json; } /** * Read a JSONArray into a List<? extends Jsonable> * Items are read until either the JSONArray is empty or the List is full. * * @param json the JSONArray * @param list the list to read into * @throws JSONException */ public static void listFromJson(JSONArray json, List<? extends Jsonable> list) throws JSONException { for (int i = 0; i < json.length() && i < list.size(); i++) { list.get(i).fromJson(json.getJSONObject(i)); } } public static List<Integer> integersListFromJson(JSONArray json) throws JSONException { List<Integer> list = new ArrayList<>(); for (int i = 0; i < json.length(); i++) { list.add(json.getInt(i)); } return list; } }