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 回答