Method to deserialize generic collection:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
...
Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);
Since several people in the comments have mentioned it, here's an explanation of how the TypeToken
class is being used. The construction new TypeToken<...>() {}.getType()
captures a compile-time type (between the <
and >
) into a runtime java.lang.reflect.Type
object. Unlike a Class
object, which can only represent a raw (erased) type, the Type
object can represent any type in the Java language, including a parameterized instantiation of a generic type.
The TypeToken
class itself does not have a public constructor, because you're not supposed to construct it directly. Instead, you always construct an anonymous subclass (hence the {}
, which is a necessary part of this expression).
Due to type erasure, the TypeToken
class is only able to capture types that are fully known at compile time. (That is, you can't do new TypeToken<List<T>>() {}.getType()
for a type parameter T
.)
For more information, see the documentation for the TypeToken
class.
Just tested and this works:
public class Coordinates {
byte red;
@JsonProperty("r")
public byte getR() {
return red;
}
@JsonProperty("red")
public void setRed(byte red) {
this.red = red;
}
}
The idea is that method names should be different, so jackson parses it as different fields, not as one field.
Here is test code:
Coordinates c = new Coordinates();
c.setRed((byte) 5);
ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));
Coordinates r = mapper.readValue("{\"red\":25}",Coordinates.class);
System.out.println("Deserialization: " + r.getR());
Result:
Serialization: {"r":5}
Deserialization: 25
Best Answer
To suppress serializing properties with null values using Jackson >2.0, you can configure the
ObjectMapper
directly, or make use of the@JsonInclude
annotation:or:
Alternatively, you could use
@JsonInclude
in a getter so that the attribute would be shown if the value is not null.A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.