Gson - convert from Json to a typed ArrayList<T>
You may use TypeToken to load the json string into a custom object.
logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
Documentation:
Represents a generic type T.
Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
For example, to create a type literal for
List<String>
, you can create an empty anonymous inner class:
TypeToken<List<String>> list = new TypeToken<List<String>>() {};
This syntax cannot be used to create type literals that have wildcard parameters, such as
Class<?>
orList<? extends CharSequence>
.
Kotlin:
If you need to do it in Kotlin you can do it like this:
val myType = object : TypeToken<List<JsonLong>>() {}.typeval logs = gson.fromJson<List<JsonLong>>(br, myType)
Or you can see this answer for various alternatives.
Your JSON sample is:
{ "status": "ok", "comment": "", "result": { "id": 276, "firstName": "mohamed", "lastName": "hussien", "players": [ "player 1", "player 2", "player 3", "player 4", "player 5" ]}
so if you want to save arraylist of modules in your SharedPrefrences so :
1- will convert your returned arraylist for json format using this method
public static String toJson(Object jsonObject) { return new Gson().toJson(jsonObject);}
2- Save it in shared prefreneces
PreferencesUtils.getInstance(context).setString("players", toJson((.....ArrayList you want to convert.....)));
3- to retrieve it at any time get JsonString from Shared preferences like that
String playersString= PreferencesUtils.getInstance(this).getString("players");
4- convert it again to array list
public static Object fromJson(String jsonString, Type type) { return new Gson().fromJson(jsonString, type);}ArrayList<String> playersList= (ArrayList<String>) fromJson(playersString, new TypeToken<ArrayList<String>>() { }.getType());
this solution also doable if you want to parse ArrayList of ObjectsHope it's help you by using Gson Library .
Kotlin
data class Player(val name : String, val surname: String)val json = [ { "name": "name 1", "surname": "surname 1" }, { "name": "name 2", "surname": "surname 2" }, { "name": "name 3", "surname": "surname 3" }]val typeToken = object : TypeToken<List<Player>>() {}.typeval playerArray = Gson().fromJson<List<Player>>(json, typeToken)
OR
val playerArray = Gson().fromJson(json, Array<Player>::class.java)