我使用Spring實現了一個REST風格的Web服務,並使用Jackson JSON作爲JSON對象的序列化器/反序列化器。Jackson JSON,REST數據綁定和HashMaps問題
但是我碰到錯誤415的時候要被反序列化對象包含一個HashMap:
private Map<String, String> requestMap = new HashMap<String, String>();
如果我刪除這一點,一切都完美。這是一個已知的問題?有沒有修復?
感謝, 斯里蘭卡
我使用Spring實現了一個REST風格的Web服務,並使用Jackson JSON作爲JSON對象的序列化器/反序列化器。Jackson JSON,REST數據綁定和HashMaps問題
但是我碰到錯誤415的時候要被反序列化對象包含一個HashMap:
private Map<String, String> requestMap = new HashMap<String, String>();
如果我刪除這一點,一切都完美。這是一個已知的問題?有沒有修復?
感謝, 斯里蘭卡
嚴格地說,傑克遜從接口類型引用序列化就好了。以下說明了這一點。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
public class Foo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
Map<String, String> requestMap = new HashMap<String, String>();
requestMap.put("one", "1");
requestMap.put("two", "2");
System.out.println(mapper.writeValueAsString(requestMap));
// output: {"two":"2","one":"1"}
List<UserPermission> userPermissions = new ArrayList<UserPermission>();
userPermissions.add(new UserPermissionImpl("domain1"));
userPermissions.add(new UserPermissionImpl("domain2"));
System.out.println(mapper.writeValueAsString(userPermissions));
// output: [{"scope":"domain1"},{"scope":"domain2"}]
Container container = new ContainerImpl(requestMap, userPermissions);
// From an Interface-type reference, where the implementation is an object with two Interface-type references:
System.out.println(mapper.writeValueAsString(container));
// {"requestMap":{"two":"2","one":"1"},"userPermissions":[{"scope":"domain1"},{"scope":"domain2"}]}
}
}
interface UserPermission {}
class UserPermissionImpl implements UserPermission
{
public String scope;
UserPermissionImpl(String scope) { this.scope = scope; }
}
interface Container {}
class ContainerImpl implements Container
{
public Map<String, String> requestMap;
public List<UserPermission> userPermissions;
ContainerImpl(Map<String, String> requestMap, List<UserPermission> userPermissions)
{ this.requestMap = requestMap; this.userPermissions = userPermissions; }
}
有系統中的一些其他問題,您正在使用。
這可能是正確的。我不太確定,這個線程已經過了幾個月的時間,我已經轉移了項目,所以我無法在該代碼基礎上測試它,但是當我有時間時我會玩。 :-) – Sri 2011-07-12 02:44:35
Spring和Jersey將有趣的事情添加到JSON處理中。有幾件事情需要特殊配置才能獲得傑克遜的默認行爲。如果您偶然發現了發生了什麼,請發佈更新。我確信我不是唯一好奇的人。 – 2011-07-12 03:42:23
發現了這個問題。傑克遜JSON在接口方面遇到困難。所以在定義中,使用HashMaps和ArrayLists而不是地圖和列表。不知道這是否是一個完美的解決方案,但它適用於我。
「發現問題,傑克遜JSON在接口方面遇到困難。」 - 請詳細說明。傑克遜有什麼界面有困難?你發現的問題具體是什麼?傑克遜項目網站記錄了相應的問題嗎? – 2011-07-11 10:52:44
不知道該錯誤是否被記錄,或者它是否是一個錯誤。我的意思是它不會反序列化一個列表,但會反序列化爲ArrayList。 – Sri 2011-07-11 13:04:04
如果Jackson不支持序列化對象,那麼您將得到415。你能擴展你的問題來展示一個包含地圖的類的更完整的例子嗎? – skaffman 2011-04-13 11:05:57
@skaffman ..這裏是類https://gist.github.com/919959 ..它也有公共getters和setter – Sri 2011-04-14 17:14:45
我沒有看到任何'地圖'在那裏。 – skaffman 2011-04-14 18:03:32