Android中的JSON数据日期格式问题

时间:2018-09-16 19:13:50

标签: java android arrays json api

我正在尝试从Guardian API获取一些数据。

{  
"response":{  
    "status":"ok",
    "userTier":"developer",
    "total":13662,
    "startIndex":1,
    "pageSize":10,
    "currentPage":1,
    "pages":1367,
    "orderBy":"relevance",
    "results":[  
        {  
            "id":"news/2018/jul/18/debate-continues-over-labours-code-on-antisemitism",
            "type":"article",
            "sectionId":"news",
            "sectionName":"News",
            "webPublicationDate":"2018-07-18T17:10:48Z",
            "webTitle":"Debate continues over Labour’s code on antisemitism | Letters",
            "webUrl":"https://www.theguardian.com/news/2018/jul/18/debate-continues-over-labours-code-on-antisemitism",
            "apiUrl":"https://content.guardianapis.com/news/2018/jul/18/debate-continues-over-labours-code-on-antisemitism",
            "fields":{  
                "headline":"Debate continues over Labour’s code on antisemitism"
            },
            "isHosted":false,
            "pillarId":"pillar/news",
            "pillarName":"News"
        },

这是JSON文件的一个块。我感兴趣的字段是“ sectionName”,“ webPublicationDate”,“ webTitle”,“ webUrl”和“ headline”。下面是解析它的代码:

try {
        JSONObject baseJsonResponse = new JSONObject(newsJSON);
        JSONArray newsArray = baseJsonResponse.getJSONArray("response");
        for(int i = 0; i < newsArray.length(); i++) {
            JSONObject currentNews = newsArray.getJSONObject(i);
            JSONObject details = currentNews.getJSONObject("results");

            String header = details.getString("webTitle");
            String section = details.getString("sectionName");
            long date = details.getLong("webPublicationDate");
            String url = details.getString("webUrl");

            JSONObject detailHeadline = currentNews.getJSONObject("fields");

            String headline = detailHeadline.getString("headline");

            pojo pojo = new pojo(headline, header, section, date, url);
            newsPojo.add(pojo);
        }
    } catch (JSONException e){
        Log.e(LOG_TAG, "Problem parsing the news JSON results", e);
    }
    return newsPojo;

该应用程序刚刚崩溃,日志消息显示为:dailybugle.NewsAdapter.getView(NewsAdapter.java:43) 这是第43-47行

Date dateObject = new Date(currentNewItem.getTime());
    TextView dateView = (TextView) listItemView.findViewById(R.id.news_date);
    String formattedDate = formatdate(dateObject);
    dateView.setText(formattedDate);

这是格式化的日期函数:

public String formatdate(Date dateObject) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy");
    return dateFormat.format(dateObject);
}

0 个答案:

没有答案