java jackson:从url rest web service调用pojo' s(内部pojo' s)作为json并将它们映射回pojo

时间:2015-07-30 11:13:47

标签: java json rest jackson

我使用杰克逊,情景是:

  1. 在客户端(Android)中生成对Web服务的URL调用
  2. 网络服务返回"复杂的pojo" (作为其他pojo的班级成员)作为json
  3. 返回客户端地图json to pojo
  4. 我不知道如何完成此代码以使事情有效,虽然我搜遍了所有并找出了以下起点,但后来我完全堆叠了,我需要帮助......

    1. "复杂的pojo":

      public class MyPojo {
          private List<MyOtherPojo> myOtherPojo;
          private List<HashMap<String, String>> listOfMaps;
          private Map<String, String> map;
          //Constructors, getters & setters
      }
      
    2. 客户代码:

      String wsURI = "server.com/myservice?param1=a&param2=b";
      try {
          URL url = new URL(wsURI);
          URLConnection connection = url.openConnection();
          BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          StringBuilder sbuilder = new StringBuilder();
          String aux = "";
          while ( (aux = in.readLine()) != null) {
              sbuilder.append(aux);
          }
          ObjectMapper mapper = new ObjectMapper();
          //TODO get myPojo object from his representation as string at sbuilder.toString(); 
          myPojo = ???;
      } catch (Exception e) {}
      

1 个答案:

答案 0 :(得分:2)

解决方案感谢@peeskillet:

MyPojo myPojo = mapper.readValue(connection.getInputStream(), MyPojo.class);