2017-01-10 5331 views
1

我想在我的spring引导项目中读取json。springboot无法反序列化-HttpMessageNotReadableException

我的JSON数据如下:

[{ 
    "userId":"101" 
}, 
{ 
    "partNum":"aaa" 
}, 
{ 
    "partNum":"bbb" 
}, 
{ 
    "partNum":"ccc" 
}] 

我创建了一个DTO类:

public class TcPartDto { 
    private String userId; 
    private List<String> partNum; 

    public String getUserId() { 
     return userId; 
    } 
    public void setUserId(String userId) { 
     this.userId = userId; 
    } 
    public List<String> getPartNum() { 
     return partNum; 
    } 
} 

,我在我的控制器如下称之为:

@RequestMapping(value = "/volumeinfo", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"}) 
@ResponseBody 
public List<TcPartVolumeDto> volumeinfo(@RequestBody TcPartDto partList) throws Exception { 
    return tcService.fetchVolumeInfo(partList); 
} 

但我得到以下错误:

通过邮差我得到这个错误:

"Could not read document: Can not deserialize instance of tc.service.model.TcPartDto out of START_ARRAY token\n at [Source: [email protected]; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of tc.service.model.TcPartDto out of START_ARRAY token\n at [Source: [email protected]; line: 1, column: 1]"

什么错我在干嘛?

回答

0

您创建不匹配它试图读取JSON数据的DTO。

根据您的DTO样品JSON应该是:

{ 
    "userId" : "someId", 
    "partNum" : [ "partNum1", "partNum2"] 
} 

否则,如果你是那么固定的消费JSON对象DTO应该是:

public class MyDTO { 

    private String userId; 
    private String partNum; 

    // ... 
} 

并用的参数控制器类型

List<MyDTO> 
+0

这适用于我!谢谢 –

0

您正在向您的public List<TcPartVolumeDto> volumeinfo(@RequestBody TcPartDto partList)方法发送JSON数组。但它应该反序列化为一个对象:TcPartDto partList

更改JSON结构只发送一个TcPartDto或确保您,您的volumeinfo方法可以接收ArrayList

而且你必须改变你的情况下JSON结构要发送的单个对象:

{ 
    "userId": 101, 
    "partNum": [ 
    "aaa", 
    "bbb", 
    "ccc" 
    ] 
} 
+0

我不能改变这样的JSON格式,它从另一个应用程序生成,我必须使用它作为 –

0

正如其他人已经指出了各种答案。

如果万一这是​​要映射不改变类的JSON:

JSON:

[{ 
    "userId":"101" 
}, 
{ 
    "partNum":"aaa" 
}, 
{ 
    "partNum":"bbb" 
}, 
{ 
    "partNum":"ccc" 
}] 

类:

@JsonIgnoreProperties(ignoreUnknown=true) 
public class TcPartDto { 

    private String userId; 
    private List<String> partNum; 
//getters and setters 
} 

控制器:

@RequestMapping(value = "/volumeinfo", method = RequestMethod.POST, consumes = {"application/json"}, produces = {"application/json"}) 
@ResponseBody 
public List<TcPartVolumeDto> volumeinfo(@RequestBody TcPartDto[] partArray) throws Exception { 
    return tcService.fetchVolumeInfo(partArray); 
} 

输出:

[{"userId":"101","partNum":null},{"userId":null,"partNum":["aaa"]},{"userId":null,"partNum":["bbb"]},{"userId":null,"partNum":["ccc"]}]