【问题标题】:Java: Send Date Object as JSONObject through Parse.com REST APIJava:通过 Parse.com REST API 将日期对象作为 JSONObject 发送
【发布时间】:2014-10-01 20:00:59
【问题描述】:

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

我在他们的文档中找到了关于如何在使用 REST API 时在对象中添加日期字段的说明:

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());
}

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

【问题讨论】:

  • 您可以更改时间格式以适应 ISO 8601: DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
  • 没错,原来是这个问题。我只是没有正确格式化它。

标签: java json date parse-platform jsonobject


【解决方案1】:

您的格式与他们要求的格式不符。例如:

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)吗?

【讨论】:

  • 成功了!你是对的,这是唯一的问题。谢谢您的帮助。我试过只发送标准的 Date 对象,但它没有自动转换。我需要在发送前手动格式化。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 2015-05-06
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多