将Java Spring Rest Controller中的JSON映射到POJO

时间:2016-05-17 12:46:54

标签: java json spring

我将以下JSON对象发送到我的Java Spring应用程序

{
    "ewsUrl":"https://dummy.url.com",
    "ewsIdentityToken":"12345",
    "itemIds":["itemids"],
    "entityId":null,
    "documentType":"Dummy",
    "documentStatus":"Record",
    "filename":"message.eml",
    "metadata":{"title":"message"}
}

我已经定义了一个对象public class RequestObject,并且在我的控制器中我已经

  public RequestObject 
    testMyStuff(@CurrentUser User currentUser, 
    @RequestBody RequestObject myDummyObject) throws Exception {
       return myDummyObject
    }

我的应用程序返回错误Could not read document: Root name 'ewsUrl' does not match expected ('RequestObject') for type...etc

但是,如果我发送格式为这样的JSON,它会成功映射对象:

{ "RequestObject":
    {
        "ewsUrl":"https://dummy.url.com",
        "ewsIdentityToken":"12345",
        "itemIds":["itemids"],
        "entityId":null,
        "documentType":"Dummy",
        "documentStatus":"Record",
        "filename":"message.eml",
        "metadata":{"title":"message"}
    }
}

我不想在我的JSON中命名对象,我想按照第一个例子中的描述发送。我如何实现这一目标?

更新:

RequestObject.java

public class RequestObject {

    public String ewsUrl;
    public String ewsIdentityToken;
    public String[] itemIds;
    public String entityId;
    public String documentType;
    public String documentStatus;
    public String filename;
    public Metadata metadata;

    public RequestObject() {
    }

    public static class Metadata {
        public String title;
    }
}

UPDATE2:

this example中描述的方式表明该对象不需要在POST请求的JSON数据中命名。我想我正在效仿这个例子,但我得到了不同的结果。 我缺少Jackson / Spring的配置吗?

更新3:

完整的错误消息是:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: 
Could not read document: 
Root name 'ewsUrl' does not match expected ('RequestObject') for type 
[simple type, class uk.co.test.RequestObject] at [Source: 
java.io.PushbackInputStream@7e223182; line: 2, column: 9]; 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: 
Root name 'ewsUrl' does not match expected ('RequestObject') for type 
[simple type, class uk.co.test.RequestObject]

2 个答案:

答案 0 :(得分:2)

有一些配置设置看起来像是可以为控制根元素行为的ObjectMapper定义的:

默认情况下,根据文档禁用UNWRAP_ROOT_MODULE,因此不确定为什么您会看到自己的行为。

弹簧的配置示例可在 https://fasterxml.github.io/jackson-databind/javadoc/2.0.0/com/fasterxml/jackson/databind/DeserializationFeature.html#UNWRAP_ROOT_VALUE

答案 1 :(得分:0)

只需使用JSONArray代替JSONObject

<强>更新

您可以通过JSONArray.getJSONObject()

获取您的Json对象