问题
How can I serialize and deserialize this object with gson to json:
public class test{
@Expose
public List< Pair<Double,Double> > list;
@Expose
public int alpha;
}
I've tried this:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String str = gson.toJson(testInstance,test.class);
where testInstance is an instance of class test, but it's not working because of Pair structure in List.
回答1:
You have configured Gson
object using excludeFieldsWithoutExposeAnnotation
method.
From documentation:
Configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
Could you change Pair class? If yes, you have to add @Expose
annotation to each property which you want serialize to JSON. If no, you can create similar class in your program and add annotations.
回答2:
if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure
. You can solve this problem by specifying the correct parameterized type for your generic type.
Try parameterized type like List<String>
. This should work
来源:https://stackoverflow.com/questions/17750372/serialize-object-using-gson