1) Convert json array to arraylist
Gson gson = new Gson();
JSONArray jsonArray = NetworkUtilities.getData("mymodeldata");
Type listType = new TypeToken<List<MyModel>>(){}.getType();
List<MyModel> myModelList = gson.fromJson(jsonArray, listType);
2)Arraylist to jsonArray
List<Customer> customerList = CustomerDB.selectAll(); JsonArray result = (JsonArray) new Gson().toJsonTree(customerList, new TypeToken<List<Customer>>() { }.getType());
public class Test {
public static void main (String[] args) { // Initialize a list of type DataObject List<DataObject> objList = new ArrayList<DataObject>(); objList.add(new DataObject(0, "zero")); objList.add(new DataObject(1, "one")); objList.add(new DataObject(2, "two")); // Convert the object to a JSON string String json = new Gson().toJson(objList); System.out.println(json); // Now convert the JSON string back to your java object Type type = new TypeToken<List<DataObject>>(){}.getType(); List<DataObject> inpList = new Gson().fromJson(json, type); for (int i=0;i<inpList.size();i++) { DataObject x = inpList.get(i); System.out.println(x); } }
No comments:
Post a Comment