2017-06-19 199 views
-1

我已經從我的氣象數據進行解析我是能夠成功地提取描述,最小和最大溫度,但日期是未知格式如何處理的日期將其轉換成可讀格式JSON日期解析

"list":[ 
    { 
    "dt":1497852000, 
    "temp":{ 
     "day":301.14, 
     "min":294.81, 
     "max":301.14, 
     "night":294.81, 
     "eve":301.14, 
     "morn":301.14 
    }, 
"pressure":990.68, 
    "humidity":88, 
    "weather":[ 
     { 
      "id":501, 
      "main":"Rain", 
      "description":"moderate rain", 
      "icon":"10d" 
     } 

我的代碼:

public static void JSONParsing(String forecastJsonStr) throws JSONException { 
    double MinTemp; 
    double MaxTemp; 
    String Date,description; 
    JSONObject forecastDate = new JSONObject(forecastJsonStr); 
    JSONArray ForecastData = forecastDate.getJSONArray("list"); 
    for(int i =0 ; i< ForecastData.length();i++){ 
     JSONObject weather = ForecastData.getJSONObject(i); 
     JSONObject Data = weather.getJSONObject("temp"); 
     JSONObject Description = weather.getJSONArray("weather").getJSONObject(0); 
     description = Description.getString("description"); 
     MinTemp = Data.getDouble("min"); 
     MaxTemp = Data.getDouble("max"); 


    } 
} 
+0

格式是什麼,它實際上在在JSON內? –

+0

您的日期用'dt'表示,您可以將解決方案集成到您的代碼中 –

回答

1

你的日期是seconds作爲long類型,以便獲取dt只要再用1000乘以把它轉換成miliseconds使用DateSimpleDateFormat

1)獲取您的日期作爲long

2)它傳遞Date類的構造函數,而與1000乘以它轉換成秒milisecond

3)創建和應用SimpleDateFormat得到你的約會

String s1 ="{\"dt\":1497852000}"; 
    JSONObject jsonObject2 = new JSONObject(s1); 

    java.util.Date date=new java.util.Date(jsonObject2.getLong("dt")*1000); 
    SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yy"); 
    String dateText = date_format.format(date); 
    System.out.println(dateText); 

輸出:

19/06/17 

注:由於不完整的JSONResponse,所以我只是增加了一個簡單的例子證明您的問題

0

你可以像這樣的格式,

try { 
     JSONObject responseObject = new JSONObject(response); 


     JSONArray listJsonArray = responseObject.optJSONArray("list"); 

     if (listJsonArray == null || listJsonArray.length() == 0) { 
      return; 
     } 

     for (int i = 0; i < listJsonArray.length(); i++) { 
      JSONObject eachDayJson = listJsonArray.optJSONObject(i); 

      if (eachDayJson == null) { 
       continue; 
      } 

      long dateInSeconds = eachDayJson.optLong("dt"); // Get date as seconds 

      SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm"); 

      String readableDate = format.format(new Date(dateInSeconds * 1000)); // convert that in milliseconds 

     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    }