We can convert a JSON array to a list using the ObjectMapper class. It has a useful method readValue() which takes a JSON string and converts it to the object class specified in the second argument.
The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. GSON also has two other parsers. The Gson JSON parser which can parse JSON into Java objects, and the JsonReader which can parse a JSON string or stream into tokens (a pull parser).
Both Gson. toJson() and JSONObjet. toString() have the same effect. They map your JSON object and return to you as a String.
This example demonstrate about how to convert ArrayList to string using GSON library. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code in build. gradle.
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>>() {}.type
val 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 Objects Hope 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>>() {}.type
val playerArray = Gson().fromJson<List<Player>>(json, typeToken)
OR
val playerArray = Gson().fromJson(json, Array<Player>::class.java)
Why nobody wrote this simple way of converting JSON string in List ?
List<Object> list = Arrays.asList(new GsonBuilder().create().fromJson(jsonString, Object[].class));
If you want to use Arrays, it's pretty simple.
logs = gson.fromJson(br, JsonLog[].class); // line 6
Provide the JsonLog
as an array JsonLog[].class
If you want convert from Json to a typed ArrayList , it's wrong to specify the type of the object contained in the list. The correct syntax is as follows:
Gson gson = new Gson();
List<MyClass> myList = gson.fromJson(inputString, ArrayList.class);
I am not sure about gson but this is how you do it with Jon.sample hope there must be similar way using gson
{ "Players": [ "player 1", "player 2", "player 3", "player 4", "player 5" ] }
===============================================
import java.io.FileReader;
import java.util.List;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JosnFileDemo {
public static void main(String[] args) throws Exception
{
String jsonfile ="fileloaction/fileName.json";
FileReader reader = null;
JSONObject jsb = null;
try {
reader = new FileReader(jsonfile);
JSONParser jsonParser = new JSONParser();
jsb = (JSONObject) jsonParser.parse(reader);
} catch (Exception e) {
throw new Exception(e);
} finally {
if (reader != null)
reader.close();
}
List<String> Players=(List<String>) jsb.get("Players");
for (String player : Players) {
System.out.println(player);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With