Java:通过Parse.com REST API将日期对象作为JSONObject发送

时间:2014-08-08 10:50:46

标签: java json date parse-platform jsonobject

我正在尝试使用HttpsUrlConnection通过Parse的REST API在我的Parse.com数据库中创建一个新对象。他们的REST API只接受JSON。我已经完成了所有工作,数据库将接受新的对象条目 - 除了我尝试包含Date字段时。当我传入日期时,服务器完全拒绝该对象。

我在他们的文档中找到了这个描述,用于在使用REST API时如何在对象中添加Date字段:

  

Parse移动客户端库还支持日期,二进制数据和关系数据。在REST API中,这些值被编码为JSON哈希值,并且__type字段设置为指示其类型,因此如果使用正确的编码,则可以读取或写入这些字段。

     

Date类型包含一个字段iso,其中包含以ISO 8601格式存储的UTC时间戳,精度为毫秒级:YYYY-MM-DDTHH:MM:SS.MMMZ。

{
  "__type": "Date",
  "iso": "2011-08-21T18:02:52.249Z"
}

因此,如果我想创建一个新对象并将其传递给数据库,我假设我需要创建另一个JSONObject并在相应的字段中传递它。然而,当我尝试时,它仍然拒绝它。下面是我尝试将Date对象添加为要传递的参数,存储在自己的JSONObject中。我究竟做错了什么?根据文档在JSON中发送Date对象的正确方法是什么?

//datePicked is a Calendar object
Date sendTime = datePicked.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String sendTimeInUTC = formatter.format(sendTime);  

//Storing the Date object as a JSONObject, as specified
JSONObject dateAsObj = new JSONObject();
dateAsObj.put("__type", "Date");
dateAsObj.put("iso", sendTimeInUTC);

//jsonParam is the JSONObject that is being sent over to Parse's REST API
jsonParam.put("sendTime", dateAsObj);

这是完整的函数,它为上下文和引用提供http请求:

private void runHttpRequest(final String emailAddress, final String password,
        String[] recipients, final String title, final String message) throws MalformedURLException {
    //Stores email in Parse DB, from Java servlet
    String url = "https://api.parse.com/1/classes/Email";
    URL obj = new URL(url);
    HttpsURLConnection con = null;
    try {
        con = (HttpsURLConnection) obj.openConnection();
    } catch (IOException e) {
        System.out.println("Failed to connect to http link");
        e.printStackTrace();
    }

    //add request header
    try {
        con.setRequestMethod("POST");
    } catch (ProtocolException e) {
        System.out.println("Failed to set to POST");
        e.printStackTrace();
    }
    con.setRequestProperty("X-Parse-Application-Id", "*****************");
    con.setRequestProperty("X-Parse-REST-API-Key", "*******************");
    con.setRequestProperty("Content-Type", "application/json");

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("username", "******");
    jsonParam.put("emailID", 1);
    jsonParam.put("universalID", "******");
    Gson converter = new Gson();
    String recipientsInJson = converter.toJson(recipients);
    jsonParam.put("to", recipientsInJson);
    jsonParam.put("from", emailAddress);
    jsonParam.put("title", title);
    jsonParam.put("body", message);

    Date sendTime = datePicked.getTime();
    //jsonParam.put("sendTime", sendTime);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    String sendTimeInUTC = formatter.format(sendTime);
    System.out.println("UTC time" + sendTimeInUTC);

    JSONObject dateAsObj = new JSONObject();
    dateAsObj.put("__type", "Date");
    dateAsObj.put("iso", sendTimeInUTC);
    System.out.println(dateAsObj.toString());

    jsonParam.put("sendTime", dateAsObj);

    String urlParameters = jsonParam.toString();

    // Send POST request
    con.setDoOutput(true);
    DataOutputStream wr = null;
    try {
        wr = new DataOutputStream(con.getOutputStream());
    } catch (IOException e1) {
        System.out.println("Failed to get output stream");
        e1.printStackTrace();
    }
    try {
        wr.writeBytes(urlParameters);
    } catch (IOException e) {
        System.out.println("Failed to connect to send over Parse object as parameter");
        e.printStackTrace();
    }
    try {
        wr.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        wr.close();
    } catch (IOException e) {
        System.out.println("Failed to connect to close datastream connection");
        e.printStackTrace();
    }

    int responseCode = 0;
    try {
        responseCode = con.getResponseCode();
    } catch (IOException e) {
        System.out.println("Failed to connect to get response code");
        e.printStackTrace();
    }
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = null;
    try {
        in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
    } catch (IOException e) {
        System.out.println("Failed to get input stream");
        e.printStackTrace();
    }
    String inputLine;
    StringBuffer response = new StringBuffer();

    try {
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    } catch (IOException e) {
        System.out.println("Failed to read line");
        e.printStackTrace();
    }
    try {
        in.close();
    } catch (IOException e) {
        System.out.println("Failed to close input stream");
        e.printStackTrace();
    }

    //print result
    System.out.println(response.toString());
}

任何帮助或意见都将不胜感激。

2 个答案:

答案 0 :(得分:5)

您的格式与他们所要求的格式不匹配。例如:

Theirs: 2011-08-21T18:02:52.249Z
Yours:  2011-08-21 18:02:52.249

您错过了TZ

因此,请尝试将格式更改为:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

说实话,如果这不是自动处理的话,我会感到惊讶 - 你刚试过dateAsObj.put("iso", sendTime)吗?

答案 1 :(得分:2)

标准日期对象未存储在Parse中。您必须将其设置为"__type": "Date""iso": Date_String_you_want_to_set的JSON对象。 日期字符串格式如下:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");