2015-10-17 73 views
-1

我想從下面的JSON中獲取JSON密鑰的值,這是在運行時使用Pojo生成器創建的動態庫。Java反射幫助需要在JAVA中獲取JSON KEY的值Spring

我的代碼

 System.out.println("inside the getFilterCOndition method and the values are "+ new ObjectMapper().writeValueAsString(input)); 
     Object a = input.getClass().newInstance(); 
     System.out.println("inside the getFilterCOndition method and the values are "+new ObjectMapper().writeValueAsString(input.getClass().getDeclaredFields())); 
      Object z = input.getClass().newInstance(); 
       System.out.println("z "+ z); 
     List<String> items = Arrays.asList(props.getProperty("input.from.ui.for.filters").split(",")); 
     System.out.println("getFilterCondition loop "+ items); 



    if(input!=null && !(input==null)){ 
     System.out.println(" inside the not null loop and the value is -----The input is "+ type.getDeclaredField("obj1")); 
     //Object o = input 
     System.out.println(" inside the not null loop and the value is -----The input is "+ input.getClass().getDeclaredClasses()); 
     for (int i = 0; i < items.size(); i++) { 
      System.out.println("Inside the for loop of filtercondition "+items.get(i)); 



      if(items.get(i).split("~")[1].equalsIgnoreCase("String")){ 
       System.out.println("insid the if loop "+ "items.get(i) value is " + items.get(i)); 
       System.out.println("props.getProperty(items.get(i)).split()[0] -is-- "+items.get(i).split("~")[0]); 
       System.out.println("trying for type.getDeclaredField() -- "+ type.getDeclaredField("obj1")); 
         if(type.getDeclaredField((items.get(i)).split("~")[0])!=null){ 
          queryFilter += " AND (" + ((items.get(i))).split("~")[0]+ BPMConstants.EQUALS + BPMConstants.SINGLE_QUOTES + type.getDeclaredField((items.get(i)).split("~")[0]) + BPMConstants.SINGLE_QUOTES + ")"; 
           } 




          } else if(items.get(i).split("~")[1].equalsIgnoreCase("Integer")){ 
           if(type.getDeclaredField((items.get(i)).split("~")[0])!=null){ 
            queryFilter += " AND (" + ((items.get(i))).split("~")[0]+ BPMConstants.EQUALS + BPMConstants.SINGLE_QUOTES + type.getDeclaredField((items.get(i)).split("~")[0]) + BPMConstants.SINGLE_QUOTES + ")"; 
             } 
            } else if(items.get(i).split("~")[1].equalsIgnoreCase("Boolean")){ 
             if(type.getDeclaredField((items.get(i)).split("~")[0])!=null){ 
              queryFilter += " AND (" + ((items.get(i))).split("~")[0]+ BPMConstants.EQUALS + BPMConstants.SINGLE_QUOTES + type.getDeclaredField((items.get(i)).split("~")[0]) + BPMConstants.SINGLE_QUOTES + ")"; 
               } 
              } else { 
               System.out.println("inside the else final loop the props.getProperty(items.get(i)) value is "+ ((items.get(i)).split("~")[0])); 
               if(type.getDeclaredField((items.get(i)).split("~")[0])!=null){ 
               Field multiSelectItems1 = type.getDeclaredField((items.get(i)).split("~")[0]); 
                //List<Field> multiSelectItems = Arrays.asList(multiSelectItems1); 
                List<String> multiSelectItems = Arrays.asList((multiSelectItems1.getName().split(","))); 
                queryFilter += " AND ("; 
                for (int j = 0; j < multiSelectItems.size(); j++) { 
                 queryFilter += ((items.get(i))).split("~")[0]+ BPMConstants.EQUALS + BPMConstants.SINGLE_QUOTES + multiSelectItems.get(j) + BPMConstants.SINGLE_QUOTES; 
                if(j< multiSelectItems.size()-1){ 
                 queryFilter += " OR "; 
                } 
               } 
                queryFilter += ")"; 
               } 
          } 
       } 
     System.out.println("The QueryFilter frmaed before replacing the characters --- "+queryFilter); 
     /*queryFilter = queryFilter.replaceFirst(" AND (", ""); 
     queryFilter = queryFilter.replaceFirst(")", "");*/ 
     } 

控制檯中的樣品是:::

INFO: Server startup in 13901 ms 
[2015-10-17 20:39:48,693]:org.springframework.web.servlet.DispatcherServlet-[DEBUG]: DispatcherServlet with name 'bpm-service' processing POST request for [/Inbox/bpm/getGrid] 
[2015-10-17 20:39:48,701]:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping-[DEBUG]: Looking up handler method for path /bpm/getGrid 
[2015-10-17 20:39:48,706]:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping-[DEBUG]: Returning handler method [public com.db.checklist.model.wrapper.TaskEODOutput com.db.checklist.controller.RestController.getGrid(javax.servlet.http.HttpServletRequest,com.db.checklist.model.wrapper.TaskInput)] 
[2015-10-17 20:39:48,707]:org.springframework.beans.factory.support.AbstractBeanFactory-[DEBUG]: Returning cached instance of singleton bean 'restController' 
[2015-10-17 20:39:48,813]:org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver-[DEBUG]: Reading [class com.db.checklist.model.wrapper.TaskInput] as "application/json;charset=UTF-8" using [org.springfr[email protected]7e7642b3] 
inside the getFilterCOndition method and the values are [{"obj3":"one,two,three,four,five","obj4":true,"obj1":"String1","obj2":35}] 
inside the getFilterCOndition method and the values are [{"name":"serialVersionUID","type":"long","modifiers":26,"annotations":[],"declaredAnnotations":[],"declaringClass":"java.util.ArrayList","synthetic":false,"genericType":"long","enumConstant":false,"accessible":false},{"name":"DEFAULT_CAPACITY","type":"int","modifiers":26,"annotations":[],"declaredAnnotations":[],"declaringClass":"java.util.ArrayList","synthetic":false,"genericType":"int","enumConstant":false,"accessible":false},{"name":"EMPTY_ELEMENTDATA","type":"[Ljava.lang.Object;","modifiers":26,"annotations":[],"declaredAnnotations":[],"declaringClass":"java.util.ArrayList","synthetic":false,"genericType":"[Ljava.lang.Object;","enumConstant":false,"accessible":false},{"name":"elementData","type":"[Ljava.lang.Object;","modifiers":130,"annotations":[],"declaredAnnotations":[],"declaringClass":"java.util.ArrayList","synthetic":false,"genericType":"[Ljava.lang.Object;","enumConstant":false,"accessible":false},{"name":"size","type":"int","modifiers":2,"annotations":[],"declaredAnnotations":[],"declaringClass":"java.util.ArrayList","synthetic":false,"genericType":"int","enumConstant":false,"accessible":false},{"name":"MAX_ARRAY_SIZE","type":"int","modifiers":26,"annotations":[],"declaredAnnotations":[],"declaringClass":"java.util.ArrayList","synthetic":false,"genericType":"int","enumConstant":false,"accessible":false}] 
z [] 
getFilterCondition loop [obj1~String, obj2~integer, obj3~List<String>, obj4~boolean, obj5~boolean] 
queryFilter final - 
prinitng the filter objects -- [{"obj3":"one,two,three,four,five","obj4":true,"obj1":"String1","obj2":35}] 
The final queryFilter to be sent will be as -- 
java.lang.NoSuchFieldException: obj1 
    at java.lang.Class.getDeclaredField(Class.java:1953) 
    at com.db.checklist.service.BPMServiceImpl.getFilterCondition(BPMServiceImpl.java:565) 
    at com.db.checklist.service.BPMServiceImpl.getGrid(BPMServiceImpl.java:335) 
    at com.db.checklist.controller.RestController.getGrid(RestController.java:90) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:606) 
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) 
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) 
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) 
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) 
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) 
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870) 
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) 
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) 
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) 
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) 
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) 
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) 
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) 
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) 
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) 
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) 
    at java.lang.Thread.run(Thread.java:745) 
[2015-10-17 20:39:48,973]:org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor-[DEBUG]: Written [[email protected]] as "application/json;charset=UTF-8" using [org.springfr[email protected]7e7642b3] 
[2015-10-17 20:39:48,974]:org.springframework.web.servlet.DispatcherServlet-[DEBUG]: Null ModelAndView returned to DispatcherServlet with name 'bpm-service': assuming HandlerAdapter completed request handling 
[2015-10-17 20:39:48,974]:org.springframework.web.servlet.FrameworkServlet-[DEBUG]: Successfully completed request 

輸入是:`

[{"obj3":"one,two,three,four,five","obj4":true,"obj1":"String1","obj2":35}] 

我不能讓「OBJ1的價值「」obj2「」obj3「」obj4「」obj5「...

+0

我不是這方面的專家,但錯誤似乎不言自明。 –

+0

我嘗試了谷歌和refletions站點的所有組合,但我無法破解它。任何幫助都是可以評估的 – KaMaL

+0

你需要提供更多的代碼 - 一個片段是不夠的。具體來說,發生在例外行的情況以及指示該行是什麼將會非常有用 – tddmonkey

回答

-1

這工作對我來說,最簡單的方法是

轉換對象轉換成String GSON如再次如下

String output = new Gson().toJSon(input); 

轉換爲JSON陣列由於輸入到我是一個JSONARRAY大小爲1

JSONArray js = new JSONArray(output); 

迭代通過JSONARRAY通過

js.getJSONObject(index).getString() or js.getJSONObject(index).getInt() 

不管它可能是讓現場。