我使用Gson
反序列化一些JSON字符串實例化接口(實際上這是JWT)通過由HTTP標頭。該json包含:GSON:從JSON字符串
[
{"authority":"a1"},
{"authority":"a2"},
{"authority":"a3"},
.
.
.
{"authority":"a4"},
]
in JsonElement
。 我想上面的部分被反序列化到現場(在某些類):
Set<GrantedAuthority> authorities
哪裏GrantedAuthority
是春天的接口,它有一個實現SimpleGrantedAuthority
。 SimpleGrantedAuthority
有一個構造函數的字符串:
公共SimpleGrantedAuthority(字符串AU){this.au = AU}
我需要GSON知道實現類接口GrantedAuthority
,以反序列化JSON的。我嘗試:
public class GrantedAuthorityInstanceCreator implements InstanceCreator<GrantedAuthority> {
@Override
public GrantedAuthority createInstance(Type type) {
// no such constructor
GrantedAuthority ga = new SimpleGrantedAuthority();
return ga;
}
}
但由於SimpleGrantedAuthority
沒有無參數的構造函數,我需要提供一個參數構造函數。我怎樣才能做到這一點?
如何描述涉及到的稱號?你想達到什麼目的? – waltersu
@waltersu我想反序列化json字符串到該字段,但它是一個接口類型,我不知道如何編程gson來實例化該接口使用實現'SimpleGrantedAuthority' –
爲什麼不將它們反序列化爲'SimpleGrantedAuthority',並自己創建'Set'並將它們放入集合中? –
waltersu