2017-06-19 156 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(); 
    }