私は次のクラスを持っています:
public static class TestSomething {
Integer test;
public TestSomething(Integer test) {
this.test = test;
}
// getter and setter for test
}
では、このクラスのコレクションを作成し、Gson でシリアル化します。
Collection<TestSomething> tests = Arrays.asList(
new TestSomething(1),
new TestSomething(2),
new TestSomething(3)
);
String json = new Gson().toJson(tests, new TypeToken<Collection<TestSomething>>() {}.getType());
この後、文字列json
はに設定されます
[{"test":1},{"test":2},{"test":3}]
これは素晴らしいことです。
しかし今、私のモデル クラスはすべて、Identifiable<T>
2 つのメソッドT getId()
とvoid setId(T)
. だから私はTestSomething
-class を上から
public static class TestSomething extends Identifiable<Long> {
// same as above
}
これを通過させようとするとGson.toJson()
、Gson は次の例外で終了します。
java.lang.UnsupportedOperationException: Expecting parameterized type, got class path.to.TestSomething.
Are you missing the use of TypeToken idiom?
See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener
at com.google.gson.TypeInfoFactory.getActualType(TypeInfoFactory.java:97)
...
では、この仕事を得るにはどうすればよいのでしょうか。