2016-02-16 144 views
-1

嗨,我有如下的代碼。解析json文件時出現問題

public class offlineAgent { 

    public static void main(String[] args) throws ParseException { 

     try { 

      String filename = "E://agent.xls"; 
      HSSFWorkbook hwb = new HSSFWorkbook(); 
      HSSFSheet sheet = hwb.createSheet("Ubuild_agents"); 

      HSSFRow rowhead = sheet.createRow((short) 0); 

      rowhead.createCell((short) 0).setCellValue("Agent_name"); 

      rowhead.createCell((short) 1).setCellValue("Agent_status"); 

      // Sets the authenticator that will be used by the networking code 
      // when a proxy or an HTTP server asks for authentication. 
      Authenticator.setDefault(new CustomAuthenticator()); 

      URL url = new URL(
        "http://test:8080/rest2/agents"); 

      // read text returned by server 
      BufferedReader in = new BufferedReader(new InputStreamReader(url 
        .openStream())); 

      String line; 

      while ((line = in.readLine()) != null) { 

       FileOutputStream fop = null; 
       File file; 

       file = new File("E:/Test/Results.json"); 
       fop = new FileOutputStream(file); 
       byte[] contentInBytes = line.getBytes(); 

       fop.write(contentInBytes); 
       fop.flush(); 
       fop.close(); 

      } 
      in.close(); 
      String filePath = "E:/Test/Results.json"; 

      FileReader reader = new FileReader(filePath); 

      System.out.println("The unavailability of Ubuild agents"); 

      JSONParser jsonParser = new JSONParser(); 
      Object object = jsonParser.parse(reader); 
      //JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); 
      //JSONObject structure = (JSONObject) jsonParser.get("response"); 
      // Object[] result=(Object[]) structure.get("results"); 

      //JSONArray lang = (JSONArray) structure.get("results"); 
      JSONArray lang=new JSONArray(); 
      lang.add(object); 
      System.out.println("Objects"+object); 
      System.out.println(lang.size()); 
      for (int i = 0; i < lang.size(); i++) { 

       // System.out.println("The " + i + 
       // " element of the array: "+lang.get(i)); 

      } 
      Iterator i = lang.iterator(); 

      int j = 1; 
      while (i.hasNext()) { 

       JSONObject innerObj = (JSONObject) i.next(); 

       System.out.println("i has some data"); 
       System.out.println("innerobj" +innerObj); 

       if (innerObj.get("status").equals("Offline")) { 

        // System.out.println(innerObj.get("name")); 
        // System.out.println(innerObj.get("status")); 
        HSSFRow row = sheet.createRow((short) j); 

        row.createCell((short) 0).setCellValue(
          innerObj.get("name").toString()); 

        sheet.autoSizeColumn(0); 
        row.createCell((short) 1).setCellValue(
          innerObj.get("status").toString()); 
        sheet.autoSizeColumn(1); 
        j++; 
       } 

      } 
      FileOutputStream fileOut = new FileOutputStream(filename); 
      hwb.write(fileOut); 

      fileOut.close(); 
      // Udeployagent10 crf= new Udeployagent10(); 

      try { 
       if (j != 1) { 
        Access_password_correct1 mail = new Access_password_correct1(); 
        mail.mail1(); 
       } else { 
        System.out.println("all agents are online"); 
       } 
      } catch (AddressException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (MessagingException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 

    } 

    public void mail1() throws AddressException, MessagingException { 

     String host = "mail.gmail.com"; 
     String from = "[email protected]"; 
     String to = "[email protected]"; 
     String fileAttachment = "E://Ubuild_agent.xls"; 
     Properties props; 
     MimeMessage message; 
     Session session; 
     StringBuffer msg = new StringBuffer(); 
     String msg1 = "Please find the agent details below"; 
     String msgBody; 
     /* 
     * read file 
     */ 
     try { 
      InputStream input = new BufferedInputStream(new FileInputStream(
        "E://Ubuild_agent.xls")); 
      POIFSFileSystem fs = new POIFSFileSystem(input); 
      HSSFWorkbook wb = new HSSFWorkbook(fs); 
      HSSFSheet sheet = wb.getSheetAt(0); 
      // int firstRow=sheet.getFirstRowNum(); 
      // int lastRow=sheet.getLastRowNum(); 
      msg.append("Hello Team,\n \n"); 
      msg 
        .append("The unavailability of the agent(s) will impact that are scheduled to run on the agent."); 
      Iterator rows = sheet.rowIterator(); 

      while (rows.hasNext()) { 
       HSSFRow row = (HSSFRow) rows.next(); 
       if (row.getRowNum() > 0) { 
        msg.append("\n"); 
        Iterator cells = row.cellIterator(); 

        while (cells.hasNext()) { 

         // msg.append(' '); 
         msg.append("\t"); 
         msg.append("\n"); 

         HSSFCell cell = (HSSFCell) cells.next(); 
         if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) 
          msg.append(cell.getNumericCellValue()); 
         else if (HSSFCell.CELL_TYPE_STRING == cell 
           .getCellType()) 
          msg.append(cell.getStringCellValue()); 
         else if (HSSFCell.CELL_TYPE_BOOLEAN == cell 
           .getCellType()) 
          cell.getBooleanCellValue(); 
        } 

       } 

      } 

      msg.append("\n \n \n Thanks,\n Team"); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
     // msg.append("</body></html>"); 

     msgBody = msg.toString(); 

     // Get system properties 
     props = System.getProperties(); 

     // Setup mail server 
     props.put("mail.smtp.host", host); 

     // Get session 
     session = Session.getInstance(props, null); 
     message = new MimeMessage(session); 

     // Define message 

     message.setFrom(new InternetAddress(from)); 
     message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
     // message.addRecipient(Message.RecipientType.TO, new 
     // InternetAddress.parse("[email protected],abc")); 
     message.addRecipients(Message.RecipientType.CC, InternetAddress 
       .parse("[email protected]")); 

     message 
       .setSubject("Alert: One or more agent(s) detected to be offline"); 
     // message.setText(msg1); 
     // create the message part 
     // message.setContent(o, type); 
     MimeBodyPart messageBodyPart = new MimeBodyPart(); 

     MimeBodyPart messageBodyPart1 = new MimeBodyPart(); 

     // fill message 

     messageBodyPart.setText(msgBody); 

     // messageBodyPart.getFileName(); 
     Multipart multipart = new MimeMultipart(); 

     multipart.addBodyPart(messageBodyPart); 
     // multipart.addBodyPart(msg1); 
     // Part two is attachment 
     messageBodyPart = new MimeBodyPart(); 
     DataSource source = new FileDataSource(fileAttachment); 
     messageBodyPart.setDataHandler(new DataHandler(source)); 
     StringBuffer st = new StringBuffer(fileAttachment); 
     System.out.println(st.replace(0, 2, "")); 
     String s1 = st.toString(); 

     messageBodyPart.setFileName(s1); 

     multipart.addBodyPart(messageBodyPart); 

     // Put parts in message 
     message.setContent(multipart); 

     // Send the message 
     Transport.send(message); 
     System.out.println("mail sent successfully"); 

    } 

    public static class CustomAuthenticator extends Authenticator { 

     // Called when password authorization is needed 
     protected PasswordAuthentication getPasswordAuthentication() { 

      // Get information about the request 
      String prompt = getRequestingPrompt(); 
      String hostname = getRequestingHost(); 
      InetAddress ipaddr = getRequestingSite(); 
      int port = getRequestingPort(); 
      String username = "admin"; 
      String password = "admin"; 



      // Return the information (a data holder that is used by 
      // Authenticator) 
      return new PasswordAuthentication(username, password.toCharArray()); 

     } 

    } 

} 

我在執行代碼時遇到了問題。

異常在線程 「主要」 java.lang.ClassCastException: org.json.simple.JSONArray不能在offlineAgent.main被強制轉換爲org.json.simple.JSONObject (offlineAgent.java:115)

任何人有關於這個問題的想法?

下面是JSON文件

[{ 「ID」:21, 「名」: 「SV-HSCBUILD-P2」, 「說明」:空, 「主機」:空, 「狀態」:」離線 「 」版本「: 」N/A「, 」吞吐量「:1, 」activeJobs「:0 」maxJobs「:5 」忽略「:假, 」被配置「:真 」LASTONLINE「:1434135548313」 lastOnlineString「:」6/12/15 2:59 PM「},{」id「:11,」name「:」svl-jbuild-d1-t1「,」description「:」svl-jbuild-d1-t1「 「主機」:空, 「狀態」: 「在線」, 「版本」: 「5.0.0-432508」, 「吞吐量」:1, 「activeJobs」:0, 「maxJobs」:5, 「忽略」:假的,「configured」:true,「lastOnline」:1455402039280,「lastOnlineString」:「2/13/16 5:20 PM」},{「id」:201,「name」:「T1BuildAgent」,「description」:null 「主機」:空, 「狀態」: 「在線」, 「版本」: 「6.1.0-637672」, 「吞吐量」:1, 「activeJobs」:1, 「maxJobs」:5, 「忽略」:假的, 「被配置」:真 「LASTONLINE」:1455402099897 「lastOnlineString」: 「2/13/16 5:21 PM」},{「id」:65,「name」:「Tibco-SVTIBBUILD」,「description」:null,「host」:null,「status」:「Online」 「版本」: 「5.0.0-432508」, 「吞吐量」:1, 「activeJobs」:0 「maxJobs」:5 「忽略」:假, 「被配置」:真 「LASTONLINE」:1455402542020「lastOnlineString 「:」2/13/16 5:29 PM「},{」id「:192,」name「:」Tibco_t1「,」description「:null,」host「:null,」status「:」Online「 「版本」: 「6.1.0-637672」, 「吞吐量」:1, 「maxJobs」:5 「忽略」:假, 「被配置」:假 「LASTONLINE」:1455402561953 「lastOnlineString」:「2/13/16日下午5:29「}]

+1

是不是異常消息解釋不夠? – fge

+2

您能提供導致問題的行號代碼上下文嗎?由於代碼格式不正確,很難知道哪些行/行導致錯誤。 –

+0

我想你正嘗試以不同的方式閱讀它,而不是使用JSONObject,而是嘗試在JSONArray中讀取它。看看如何讀寫java。[參考](http://www.mkyong.com/java/json-simple-example-read-and-write-json/) – gks

回答

-1

它看起來像這條線(最接近115與Object鑄造交易):

JSONObject innerObj = (JSONObject) i.next(); 

您需要檢查的原始ObjectinstanceofJSONObjectJSONArray,並根據需要進行解析。您需要能夠處理兩種對象類型。


EDIT:與該處理相關的JSON對象類型示例代碼更新。

Object o = i.next(); 
if(o instanceof JSONArray) { 
    JSONArray innerObj = (JSONArray) o; 
    // handle recursively, perhaps? 
    // you need to loop through an array here or pick out the attributes you know you need 
} else if(o instanceof JSONObject) { 
    JSONObject innerObj = (JSONObject) o; 
    // continue with your usual code 
} 
+0

json中的其他數據類型如字符串,數字和布爾值呢?該數組也可以包含這些 –

+0

「JSONArray」中的所有項都可以是您需要獲取(和投射)其值或另一個「JSONArray」的「JSONObject」。 JSON樹沒有關於數據類型的信息,這就是解析器決定的內容。 – Gorbles

+0

你可以請示例代碼im新到json? – prathesh