I am trying to make some methods that are used to make conversions from a string Json
to a data type that inherits Collection
the problem is when the data type is needed Genérico
since to make the conversion as I am defining it I need to know what type it is and I can not find The way to do it.
Attached the code of the method:
public Collection convertirJsonAColeccion(String json, Collection coleccion) throws Exception{
if(json == null || json.equals("")){ // Se valida que no esté vacía la cadena, sí lo está lanza la excepción.
throw new Exception("La cadena está vacía");
}
Type tipoColeccion = new TypeToken<Collection>(){}.getType(); // Sé que aquí debe definir el tipo de dato generico de la colección, pero como no es uno en especifico no sé como acomodarlo
Gson gson = crearGson();
coleccion = gson.fromJson(json, tipoColeccion);
return coleccion;
This is how I try it:
List<Integer> ints = new ArrayList<Integer>();
ints.add(2);
ints.add(3);
String json = parametro.convertirColeccionAJson(ints);
System.out.println(json);
List<Integer> ints2 = new ArrayList();
ints2 = (List<Integer>) parametro.convertirJsonAColeccion(json, ints2);
for(Integer intt : ints2) {
System.out.println(intt);
}
I hope you can help me, it is complicated to explain so if it is not understandable I will try to clarify it better.
UPDATE
Class:
public class ParametrosJson<T> {
....
// Metodo para convertir una cadena json a una coleccion.
public Collection<T> convertirJsonAColeccion(String json) throws Exception{
if(json == null || json.equals("")){ // Se valida que no esté vacía la cadena, sí lo está lanza la excepción.
throw new Exception("La cadena está vacía");
}
Type tipoColeccion = new TypeToken<Collection<T>>(){}.getType(); // Obtien el tipo de coleccion teniendo en cuenta los generics
// En la linea anterior es donde está el error ya que se debe definir el generic del collection algo así: Collection<Integer> entonces tomaría bien el tipo de dato
Gson gson = crearGson();
return gson.fromJson(json, tipoColeccion);
/* Nota: Al llamar el metodo se debe castear con el tipo de coleccion en el que se está guardando.
* Ejemplo:
* List<?> lista = new ArrayList();
* lista = (List<?>) convertirJsonAObjeto(json, lista); */
}
}
As I call it in the main to execute it:
List<Integer> ints2 = new ArrayList();
ParametrosJson<Integer> parametro2 = new ParametrosJson<Integer>();
ints2 = (List<Integer>) parametro2.convertirJsonAColeccion(json);
for(Integer intt : ints2) {
System.out.println(intt);
}
To use generics you have to use the
getParameterized()
class methodTypeToken
and in the function call pass the type:Call: