[JAVA]:JSONObject 修改 date 格式

JSONObject 根据指定日期格式修改dateValue :

    public JSONObject convertJsonDateValue(JSONObject jsonObject, String sourceFormat, 
        String targetFormat) throws ParseException{
        if(jsonObject == null){
            return null;
        }
        JSONArray jsonArray = jsonObject.getJSONArray("groupName");
        for(int i = 0; i < jsonArray.size(); i++){
            JSONObject jo = jsonArray.getJSONObject(i);
            String dateStr = jo.getString("dateField");
            String dateValue = convertDateString(dateStr, sourceFormat, targetFormat);
            jo.put("dateField", dateValue);
        }
        return jsonObject;
    }

    public String convertDateString(String date, String sourceFormat, String targetFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(sourceFormat);
        Date date = sdf.parse(dateStr);
        SimpleDateFormat formatter = new SimpleDateFormat(targetFormat);
        String dateValue = formatter.format(date);
        return dateValue;
    }

测试数据:

// String jsonStr = [{"name":"Jarvis","groupName":[{"key001":"value001","dateField":"2016-10-20 T 17:30:20"},{"key002":"value002","dateField":"2016-10-21 T 17:30:20"}]}]
    JSONObject jsonObject = new JSONObject(jsonStr);
    JSONObject jo = convertJsonDateValue(jsonObject, "yyyy-MM-dd 'T' HH:mm:ss", "yyyy/MM/dd HH:mm:ss");
    System.out.println(jo.toString());

版权声明:本文为hwj528原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。