1 Reply Latest reply: Jul 7, 2014 7:02 AM by TPD-Opitz RSS

    Passing a java bean name in a method

    5eab2430-e244-4091-a547-4a0d8d10ad33

      Hi all,

       

      Here I am taking response data from JSON using jackson API.I found a feature like using Jackson the properties can be set to bean properties.

       

       

      private static String readUrl(String urlString) throws Exception {
              BufferedReader reader = null;
              try {
                  URL url = new URL(urlString);
                  reader = new BufferedReader(new InputStreamReader(url.openStream()));
                  StringBuilder buffer = new StringBuilder();
                  int read;
                  char[] chars = new char[1024];
                  while ((read = reader.read(chars)) != -1) {
                      buffer.append(chars, 0, read);
                  }

                  return buffer.toString();
              } finally {

      
      
      
      
      
      


                  if (reader != null) {
                      reader.close();
                  }
              }
          }

          public static void main(String[] args) throws Exception {
              ObjectMapper mapper = new ObjectMapper();
              mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
              JsonNode root = mapper.readTree(readUrl("myUrl"));
              ArrayNode records = (ArrayNode) root.path("records");
              Iterator<JsonNode> iterator = records.getElements();
              while (iterator.hasNext()) {
                  OrderBean ord= mapper.readValue(iterator.next(),OrderBean.class);
                  System.out.println("OrderCode=" + ord.getOrderId() + " OrderDesc=" + ord.getOrderDesc());
              }
          }

       

      I got the correct output here.

       

      But now I want to generalize my method into a utility class so that I can reuse the same method for setting response data directly to respective beans as given below:-

       

      My question is how will I pass the bean object in my utility class?


      public static Object getResponseData(String response,[b]String bean[/b]) throws Exception {
              ObjectMapper mapper = new ObjectMapper();
              mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
              JsonNode root = mapper.readTree(response);
              ArrayNode records = (ArrayNode) root.path("records");
              Iterator<JsonNode> iterator = records.getElements();
             [b] Class<?> beanClass = Class.forName(bean);[/b]
              while (iterator.hasNext()) {
                 [b] beanClass = mapper.readValue(iterator.next(), Class.class);[/b]
                 
              }
              return bean;
          }