Java:通过Parse.com REST API将JSON对象作为JSONObject发送 [英] Java: Send Date Object as JSONObject through Parse.com REST API

查看:156
本文介绍了Java:通过Parse.com REST API将JSON对象作为JSONObject发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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


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



日期类型包含一个字段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是一个Calendar对象
Date sendTime = datePicked.getTime();
SimpleDateFormat formatter = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);
formatter.setTimeZone(TimeZone.getTimeZone(UTC));
String sendTimeInUTC = formatter.format(sendTime);

//将Date对象作为JSONObject存储,如指定
JSONObject dateAsObj = new JSONObject();
dateAsObj.put(__ type,Date);
dateAsObj.put(iso,sendTimeInUTC);

// jsonParam是发送到Parse的REST API的JSONObject
jsonParam.put(sendTime,dateAsObj);

以下是http请求的完整功能,用于上下文和参考:

  private void runHttpRequest(final String emailAddress,final String password,
String [] recipient,final String title,final String message)throws MalformedURLException {
//将电子邮件存储在Parse DB中,从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(无法连接到http链接);
e.printStackTrace();
}

//添加请求头
try {
con.setRequestMethod(POST);
} catch(ProtocolException e){
System.out.println(无法设置为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);

日期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();

//发送POST请求
con.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
} catch(IOException e1){
System.out.println(无法获取输出流);
e1.printStackTrace();
}
try {
wr.writeBytes(urlParameters);
} catch(IOException e){
System.out.println(无法连接发送到Parse对象作为参数);
e.printStackTrace();
}
try {
wr.flush();
} catch(IOException e){
e.printStackTrace();
}
try {
wr.close();
} catch(IOException e){
System.out.println(无法连接到关闭数据流连接);
e.printStackTrace();
}

int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch(IOException e){
System.out.println(无法连接以获取响应代码);
e.printStackTrace();
}
System.out.println(\\\
Sending'POST'请求到URL:+ url);
System.out.println(Post parameters:+ urlParameters);
System.out.println(Response Code:+ responseCode);

BufferedReader in = null;
尝试{
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
} catch(IOException e){
System.out.println(无法获取输入流);
e.printStackTrace();
}
String inputLine;
StringBuffer response = new StringBuffer();

尝试{
while((inputLine = in.readLine())!= null){
response.append(inputLine);
}
} catch(IOException e){
System.out.println(无法读取行);
e.printStackTrace();
}
try {
in.close();
} catch(IOException e){
System.out.println(无法关闭输入流);
e.printStackTrace();
}

//打印结果
System.out.println(response.toString());
}

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

解决方案

您的格式与他们所需的格式不符。例如:

 他们的:2011-08-21T18:02:52.249Z 
你的:2011-08-21 18:02:52.249

你缺少 T Z



所以尝试将您的格式更改为:

  SimpleDateFormat formatter = new SimpleDateFormat(yyyy-MM-dd'THH:mm:ss'Z);说实话,如果这个没有自动处理,我会感到惊讶 - 你试过了吗?只是 dateAsObj.put(iso,sendTime)


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.

I found this in their documentation this description for how to add a Date field in an object when using the 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.

{
  "__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?

//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:

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.

解决方案

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 T and the Z.

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

这篇关于Java:通过Parse.com REST API将JSON对象作为JSONObject发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆