Gson - convert from Json to a typed ArrayList<T>

JavaAndroidJsonGson

Java Problem Overview


Using the Gson library, how do I convert a JSON string to an ArrayList of a custom class JsonLog? Basically, JsonLog is an interface implemented by different kinds of logs made by my Android app--SMS logs, call logs, data logs--and this ArrayList is a collection of all of them. I keep getting an error in line 6.

public static void log(File destination, JsonLog log) {
    Collection<JsonLog> logs = null;
    if (destination.exists()) {
        Gson gson = new Gson();
        BufferedReader br = new BufferedReader(new FileReader(destination));
        logs = gson.fromJson(br, ArrayList<JsonLog>.class); // line 6
        // logs.add(log);
        // serialize "logs" again
    }
}

It seems the compiler doesn't understand I'm referring to a typed ArrayList. What do I do?

Java Solutions


Solution 1 - Java

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<?> or List<? 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.

Solution 2 - Java

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 .

Solution 3 - Java

> 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)

Solution 4 - 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));

Solution 5 - Java

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

Solution 6 - Java

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);

Solution 7 - Java

You have a string like this.

"[{"id":2550,"cityName":"Langkawi","hotelName":"favehotel Cenang Beach - Langkawi","hotelId":"H1266070"},
{"id":2551,"cityName":"Kuala Lumpur","hotelName":"Metro Hotel Bukit Bintang","hotelId":"H835758"}]"

Then you can covert it to ArrayList via Gson like

var hotels = Gson().fromJson(historyItem.hotels, Array<HotelInfo>::class.java).toList()

Your HotelInfo class should like this.

import com.squareup.moshi.Json

data class HotelInfo(

	@Json(name="cityName")
	val cityName: String? = null,

	@Json(name="id")
	val id: Int? = null,

	@Json(name="hotelId")
	val hotelId: String? = null,

	@Json(name="hotelName")
	val hotelName: String? = null
)

Solution 8 - Java

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);
				}			
	}
}

Solution 9 - Java

In Kotlin For sending : If you send Arraylist

Gson().toJson(arraylist)

For receiving: If you receive ArrayList

var arraylist = Gson().fromJson(argument, object : TypeToken<ArrayList<LatLng>>() {}.type)  

For sending : If you send ModelClass( e.g. LatLngModel.class)

var latlngmodel = LatlngModel()
latlngmodel.lat = 32.0154
latlngmodel.lng = 70.1254

Gson().toJson(latlngModel)

For receiving: If you receive ModelClass

var arraylist = Gson().fromJson(argument,LatLngModel::class.java )  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMLQView Question on Stackoverflow
Solution 1 - JavaAlexView Answer on Stackoverflow
Solution 2 - JavaMohamed HussienView Answer on Stackoverflow
Solution 3 - JavamurgupluogluView Answer on Stackoverflow
Solution 4 - JavaFarukTView Answer on Stackoverflow
Solution 5 - JavaAli AsadiView Answer on Stackoverflow
Solution 6 - JavaEraldoView Answer on Stackoverflow
Solution 7 - JavaShihab UddinView Answer on Stackoverflow
Solution 8 - Javaarun kongaraView Answer on Stackoverflow
Solution 9 - JavaSafal BhatiaView Answer on Stackoverflow