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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25201814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:34:03  来源:igfitidea点击:

Java: Send Date Object as JSONObject through Parse.com REST API

javajsondateparse-platformjsonobject

提问by Koolstr

I am trying to create a new object in my Parse.com database through Parse's REST API, using an HttpsUrlConnection. Their REST API only accepts JSON. I have gotten everything to work, where the database would accept the new object entry - except for when I attempt to include a Date field. When I do pass in a Date, the server rejects the object entirely.

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

I found this in their documentation this description for how to add a Date field in an object when using the REST API:

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

The Parse mobile client libraries also support dates, binary data, and relational data. In the REST API, these values are encoded as JSON hashes with the __type field set to indicate their type, so you can read or write these fields if you use the correct encoding.

The Date type contains a field iso which contains a UTC timestamp stored in ISO 8601 format with millisecond precision: YYYY-MM-DDTHH:MM:SS.MMMZ.

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

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

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

So if I want to create a new object and pass it to the database, I am assuming I need to create another JSONObject and pass it over in its corresponding field. However, when I tried that, it still rejected it. Below is my attempt at adding the Date object as a parameter to pass over, stored in its own JSONObject. What am I doing wrong? What is the right way of sendign a Date object in JSON, based on their docs?

因此,如果我想创建一个新对象并将其传递给数据库,我假设我需要创建另一个 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);

Here is the full function which makes the http request, for context and reference:

这是发出 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());
}

Any help or input would be appreciated.

任何帮助或输入将不胜感激。

采纳答案by Jon Skeet

Your format doesn't match the one they've required. For example:

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

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

You're missing the Tand the Z.

你错过了TZ

So try changing your format to:

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

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

To be honest, I'd be surprised if this weren't handled automatically though - have you tried just dateAsObj.put("iso", sendTime)?

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

回答by Girish Sharma

Standard Date Object is not stored in Parse. You have to set it as a JSON Object with "__type": "Date"and "iso": Date_String_you_want_to_set. with the date string formatted as below:

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

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