我使用Spring实现了RESTful Web服务,并使用Jackson JSON作为JSON对象的序列化器/反序列化器。
但是,当要反序列化的对象包含HashMap时,我遇到错误415:
private Map<String, String> requestMap = new HashMap<String, String>();
如果我删除它,一切都很完美。这是一个已知的问题?有没有修复?
谢谢, 斯
答案 0 :(得分:1)
严格来说,杰克逊从接口类型引用序列化就好了。以下说明了这一点。
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; }
}
您正在使用的系统中存在其他一些问题。
答案 1 :(得分:0)
发现了这个问题。 Jackson JSON在Interfaces方面遇到了困难。因此,在定义中,使用HashMaps和ArrayLists而不是Maps和Lists。不确定这是否是一个完美的解决方案,但它对我有用。