在springframework

时间:2017-11-11 15:53:04

标签: json spring angular http-post spring-framework-beans

我正在构建一个与使用Spring Framework编写的restful API进行通信的Angular应用程序。

我的类层次结构是这样的:

class Resource
class FileResource extends Resource
class DbResource extends Resource
class DbFileResource extends DbResource
class DbServerResource extends DbResource

并且我在我的post请求中发送了这样一个json对象,例如,它在我的类层次结构中包含DbServerResource:

{
"resourceName": "Res2",
"resourceType": "DB_SERVER",
"dbms": "DB2",
"dbName": "SHOP",
"host": "<some ip>",
"port": 50000,
"userName": "user",
"password": "password"
}

在我的控制器中,我有一个addResource方法:

@RequestMapping (method = RequestMethod.POST, value="/resource")
private void addResource(@RequestBody Resource resource)

我有一个Factory类,我正在调用以使用instanceof检索要使用的确切对象:

public ResourceId getResourceId(Resource res){

    if (res== null){
        return null;
    }....

但是在发送我的请求时,我收到一个NullPointerException:

  

显示java.lang.NullPointerException       COM ... ResourceManager.validateResourceId(ResourceManager.java:861)       COM ... management.resource.manager.ResourceManager.addResource(ResourceManager.java:127)

似乎工厂没有设法识别相关对象并返回null! 春天如何识别它应该映射json的对象?!或者我做错了什么!

1 个答案:

答案 0 :(得分:0)

我尝试使用这些注释: https://fasterxml.github.io/jackson-annotations/javadoc/2.4/com/fasterxml/jackson/annotation/JsonTypeInfo.html

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
            include = JsonTypeInfo.As.PROPERTY, 
            property = "resourcetype",
            visible=true)
@JsonSubTypes({
@JsonSubTypes.Type(value = DbServerResource.class, name = "dbServerResource"),
@JsonSubTypes.Type(value = DbFileResource.class, name = "dbFileResource"),
@JsonSubTypes.Type(value = FileResource.class, name = "fileResource")
})

public abstract class DisplayResource{
protected String resourceName;
@JsonProperty(value = "resourceType") protected Types resourceType;

public enum Types { DB_SERVER, DB_FILE, FILE }  

但现在当我发送POST请求时,我收到状态400错误请求!!!

我的控制器端现在看起来像这样:

@RequestMapping (method = RequestMethod.POST, value="/resource")
private @ResponseBody <T extends DisplayResource>T addResource(@RequestBody T resource) 
        throws ResourceManagementException, ConfigurationException, MalformedURLException{

    logger.info("Adding a new resource: " + resource.toString());

    ...     
    resourceManagerService.addResource("admin", resourceFactory.getResourceId(resource), credentials);

    return resource;
}

GET方法仍然正常。