从rest Web服务返回带有一些变量和ArrayList <otherpojo>的Pojo - 如何避免LinkedHasрMap转换</otherpojo>

时间:2014-12-10 23:37:30

标签: java web-services rest jackson

我的问题与更好地理解与Json合作的技术有关,并检查我是否可以采用我认为更好的做法。我正在返回ArrayList<myPojo>发送其他Web服务的响应,我无法理解为什么它总是以LinkedHashMap的形式返回它,即使我在我正在使用的模型对象中键入ArrayList<myPojo> 。有没有办法从休息网络服务返回ArrayList<myPojo>,或者我真的必须从LinkedHasMap转换为预期的对象?

例如,有没有办法,可能通过使用@Entity或其他一些注释,以避免下面的转换?我在这个问题中找到的最接近的问题是ClassCastException: RestTemplate returning List<LinkedHashMap> instead of List<MymodelClass>,但如果我能在客户端避免使用转换器并返回ArrayList<myPojO>,则它没有回答这个问题 - 一个原因是因为他没有声明像我这样的网络服务,在这种情况下@GenericArguments(RedemptionDetail.class)RedemptionDetail是完全响应,在我的情况下,ArrayList是更复杂对象(LogDisplay)的一部分。我在下面粘贴了其余的webservice相关点。

//the jars list

"aopalliance-1.0.jar"
"commons-logging-1.1.1.jar"
 "hibernate-validator-4.1.0.Final.jar"
"hibernate-validator-annotation-processor-4.1.0.Final.jar"
"jackson-annotations-2.2.3.jar"
"jackson-core-2.2.3.jar"
"jackson-databind-2.2.3.jar"
"slf4j-api-1.7.5.jar"
"slf4j-log4j12-1.7.5.jar"
"spring-aop-4.1.2.RELEASE.jar"
"spring-beans-4.1.2.RELEASE.jar"
"spring-context-4.1.2.RELEASE.jar"
"spring-context-support-4.1.2.RELEASE.jar"
"spring-core-4.1.2.RELEASE.jar"
"spring-expression-4.1.2.RELEASE.jar"
"spring-web-4.1.2.RELEASE.jar"
"spring-webmvc-4.1.2.RELEASE.jar"
"validation-api-1.0.0.GA.jar"

//rest web service
    @Controller
    public class Lo_Controller {
           @RequestMapping(value="myUrl", method=RequestMethod.POST)
           @ResponseBody

//client call
    LogDisplay _l = restTemplate.postForObject("http://localhost:8080/myApp/myRestService",myObjWithPasrameters, LogDisplay.class);

    //it will print class java.util.ArrayList
    System.out.printLn((lo_Values.setDisplayValues((_l.getDisplayValues()).getClass());

    //it will print class java.util.LinkedHashMap but I was expecting to get Lo_DisplayRecord type               
    System.out.printLn((lo_Values.setDisplayValues(_l.getDisplayValues().get(0))).getClass());

    /* when trying to cast (Lo_DisplayRecord)displayValues.get(0)
    I got the error
    java.lang.ClassCastException: java.util.LinkedHashMap
     cannot be cast to com.my_app. Lo_DisplayRecord
    so I fixed it by using jackson.map.ObjectMapper as suggested in
    https://stackoverflow.com/questions/15430715/casting-linkedhashmap-to-complex-object
    */

    //Solution 1:
    ObjectMapper mapper = new ObjectMapper();
    Lo_DisplayRecord pojo = mapper.convertValue(displayValues.get(0), Lo_DisplayRecord.class);

    //Solution 2:
    byte[] json = mapper.writeValueAsBytes(displayValues.get(0));
    Lo_DisplayRecord pojo2 = mapper.readValue(json, Lo_DisplayRecord.class);

//the pojo     
    public class LogDisplay {
    private ArrayList<Lo_DisplayRecord> displayValues;
    //... others variables not relevants to the question
    public ArrayList<Lo_DisplayRecord> getDisplayValues() {
      return displayValues;
    }

0 个答案:

没有答案