如何使用com.fasterxml.jackson.databind.ObjectMapper

时间:2016-06-14 20:44:05

标签: javascript java angularjs json spring

我正在使用angularjs处理Spring MVC项目,我从视图中传递了以下JSON数组{name:"theName", code:"theCode", comment:"theComment", listOfIds:["3", "4"]}

这是我的控制器,它接收JSON

@RequestMapping(value = "/createPerson/", method = RequestMethod.POST)
public ResponseEntity<Void> createSep(@RequestBody final String DTOJsonObject,
        UriComponentsBuilder ucBuilder) {
ObjectMapper mapper = new ObjectMapper();
        Map<String, String> dataDTOParsed ;
        dataDTOParsed = mapper.readValue(DTOJsonObject, HashMap.class);


    //I tried this but it says that a String can not be converted to ArrayList<String> 
                ArrayList<String> listIDS = new ArrayList<String>();
                listIDS = (ArrayList<String>) dataDTOParsed .get("listOfIds");
}

我尝试使用以下演员,但它说String can not be converted to ArrayList<String>

ArrayList<String> listIDS = new ArrayList<String>();
                    listIDS = (ArrayList<String>) dataDTOParsed .get(this);

我知道如何获得其他值是这个值listOfIds:["3", "4"]给我带来问题

1 个答案:

答案 0 :(得分:0)

由于您的JSON对象具有不同数据类型(String,Array ...)的属性,因此最好将其映射到Map<String, Object>然后进行相应的转换。

代码示例:

@RequestMapping(value = "/createPerson/", method = RequestMethod.POST)
public ResponseEntity<Void> createSep(@RequestBody final String DTOJsonObject,
    UriComponentsBuilder ucBuilder) {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> parsedData;

    parsedData = mapper.readValue(DTOJsonObject, HashMap.class);

    List<String> listIDS = (ArrayList<String>)parsedData.get("listOfIds");

    for(String n : listIDS){
        System.out.println(n);
    }