0

Javaを使用してJSONファイルの値を更新する必要がありますが、どういうわけか更新できません。以下は、解析しようとしているJSON形式です

{
  "recentActivities":[  
     { 
       "displayValue":"POC | Augmented Reality", 
       "link":"poc.jsp?search=augmented%20reality",
       "timestamp":"18/07/2013 17:33"
     },
     { 
       "displayValue":"POC | Image Editing in Hybrid Application", 
       "link":"poc.jsp?search=image%20editing",
       "timestamp":"18/07/2013 01:00"
     }
   ],

  "lastEmailSent": "29/06/2013 00:00"
}

現在の日付に更新lastEmailSentする必要がありますが、どういうわけか行き詰まっています。以下は私が使用している私のJavaコードです

private void updateLastEmailTimeStamp(String jsonFilePath) {
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    JSONObject lastEmailTimeStamp = new JSONObject();

    FileReader reader =null;
    try {
        File jsonFile = new File(jsonFilePath);
        reader = new FileReader(jsonFile);
        jsonObject = (JSONObject) parser.parse(reader);

        lastEmailTimeStamp = (JSONObject) jsonObject.get("lastEmailSent");

        //write current date as last mail sent time.
        writeTimeStamp(lastEmailTimeStamp, jsonFile);

        APP_LOGGER.info("last Email Sent timestamp updated");       
    } catch (IOException ex) {
        APP_LOGGER.error(ex.getLocalizedMessage(), ex);
    } catch (ParseException ex) {
        APP_LOGGER.error(ex.getLocalizedMessage(), ex);
    } 

}


private void writeTimeStamp(JSONObject lastEmailTimeStamp, File jsonFile) {
    FileWriter writer = null;
    try{
         writer = new FileWriter(jsonFile);

         String currentDate = MyDateFormatterUtility.formatDate(new Date(),"dd/MM/yyyy HH:mm");

         lastEmailTimeStamp.put(SubscriptionConstants.LAST_EMAIL_TIMESTAMP, currentDate);

         writer.write(lastEmailTimeStamp.toJSONString());
      }catch(IOException ex){
          APP_LOGGER.error(ex.getLocalizedMessage(), ex);
      }finally{
             try {
             writer.flush();
             writer.close();
             } catch (IOException ex) {
             APP_LOGGER.error(ex.getLocalizedMessage(), ex);
             }
      }
}

次の行でエラーが発生しています

lastEmailTimeStamp = (JSONObject) jsonObject.get("lastEmailSent");.

オブジェクトを正しく解析また​​はアクセスしていないと思います。誰かが私を正しくしてもらえますか?ありがとうございました!

4

2 に答える 2

0

私は@Hot Licksに同意しますが、次のようにして修正を試みることができます:

String lastEmailSent = jsonObject.getString("lastEmailSent");

また、それが問題でない場合は、ファイルからのテキストが、ここに投稿した JSON テキストと正確に一致しない可能性があります。その場合、ファイルを文字列に読み取り、ブレークポイントを追加し、文字列をチェックして、期待するすべての JSON 要素が含まれているかどうかを確認できます。

Java 7 では、次のようにテキストを読むことができます。

String content = readFile(jsonFilePath, Charset.defaultCharset());

static String readFile(String path, Charset encoding) 
    throws IOException 
{
      byte[] encoded = Files.readAllBytes(Paths.get(path));
      return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
于 2013-07-22T16:31:03.347 に答える
0

最後に、私は解決策を理解することができました。コードで次の変更が必要でした

private void updateLastEmailTimeStamp(String jsonFilePath) {
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = new JSONObject();

    FileReader reader =null;
    try {
        File jsonFile = new File(jsonFilePath);
        reader = new FileReader(jsonFile);
        jsonObject = (JSONObject) parser.parse(reader);

        jsonObject.remove("lastEmailSent");


        //write current date as last mail sent time.
        writeTimeStamp(jsonObject, jsonFile);

        APP_LOGGER.info("last Email Sent timestamp updated");       
    } catch (IOException ex) {
        APP_LOGGER.error(ex.getLocalizedMessage(), ex);
    } catch (ParseException ex) {
        APP_LOGGER.error(ex.getLocalizedMessage(), ex);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }

}


/**
 * Method to write current date as last mail sent timestamp 
 * denoting when the newsletter was sent last.
 * 
 * @param jsonObj- date for last email sent.
 * @param jsonFile - recentactivities.json file
 */
@SuppressWarnings("unchecked")
private void writeTimeStamp(JSONObject jsonObj, File jsonFile) {
    FileWriter writer = null;
    try {
        writer = new FileWriter(jsonFile);

        String currentDate = MyDateFormatter.formatDate(new Date(),"dd/MM/yyyy HH:mm");

        jsonObj.put("lastEmailSent", currentDate);


        writer.write(jsonObj.toJSONString());
    }catch(IOException ex){
        APP_LOGGER.error(ex.getLocalizedMessage(), ex);
    }finally{
        try {
            writer.flush();
            writer.close();
        } catch (IOException ex) {
            APP_LOGGER.error(ex.getLocalizedMessage(), ex);
        }
    }
}
于 2013-07-23T05:52:08.087 に答える