private XMLGregorianCalendar getXMLGregorianCalendarNow() throws DatatypeConfigurationException { GregorianCalendar gregorianCalendar = new GregorianCalendar(); DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); XMLGregorianCalendar now = datatypeFactory .newXMLGregorianCalendar(gregorianCalendar); return now; }
private Period preparePeriod(long periodStartTime, long periodEndTime) throws DatatypeConfigurationException { Period period = new Period(); DatatypeFactory df = DatatypeFactory.newInstance(); GregorianCalendar gc = new GregorianCalendar(); // start date period.setStartDate(BigInteger.valueOf(periodStartTime)); gc.setTimeInMillis(periodStartTime); period.setStartDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); // end date period.setEndDate(BigInteger.valueOf(periodEndTime)); gc.setTimeInMillis(periodEndTime); period.setEndDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); return period; }
/** * * @return An object of type XMLGregorianCalendar containing the current * system time and date * @throws DatatypeConfigurationException * If the instantiation of the DatatypeFactory fails */ public static XMLGregorianCalendar newXMLGregorianCalendarSystemTime() throws DatatypeConfigurationException { GregorianCalendar gregorianCalendar = new GregorianCalendar(); DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); XMLGregorianCalendar now = datatypeFactory .newXMLGregorianCalendar(gregorianCalendar); return now; }
@BeforeClass public static void setup() throws Exception { SharesDataRetrievalServiceLocal sharesRetrievalService = mock(SharesDataRetrievalServiceLocal.class); BillingDataRetrievalServiceLocal billingRetrievalService = mock(BillingDataRetrievalServiceLocal.class); brokerShareAssembler = spy(new BrokerShareResultAssembler( sharesRetrievalService, billingRetrievalService)); // create test data createBillingResults(); // mock service methods mockGetBrokerData(); mockGetBrokerRevenueSharePercentage(); mockGetOrgData(NUMBER_SUPPLIERS); mockGetOrgData(NUMBER_CUSTOMER); mockGetSupplierKeyForSubscription(); mockGetProductHistoryData(); mockGetSubscriptionHistoryData(); mockGetBillingResults(); mockXmlSearch(); datatypeFactory = DatatypeFactory.newInstance(); }
@Before public void setup() throws Exception { SharesDataRetrievalServiceLocal sharesRetrievalService = mock(SharesDataRetrievalServiceLocal.class); BillingDataRetrievalServiceLocal billingRetrievalService = mock(BillingDataRetrievalServiceLocal.class); resellerShareAssembler = spy(new ResellerShareResultAssembler( sharesRetrievalService, billingRetrievalService)); // create test data createBillingResults(); // mock service methods mockGetResellerData(); mockGetResellerRevenueSharePercentage(); mockGetOrgData(NUMBER_SUPPLIERS); mockGetOrgData(NUMBER_CUSTOMER); mockGetSupplierKeyForSubscription(); mockGetProductHistoryData(); mockGetSubscriptionHistoryData(); mockGetBillingResults(); mockXmlSearch(); datatypeFactory = DatatypeFactory.newInstance(); }
@BeforeClass public static void setup() throws Exception { SharesDataRetrievalServiceLocal billingRetrievalService = mock(SharesDataRetrievalServiceLocal.class); when( billingRetrievalService.loadOrganizationHistoryRoles(anyLong(), anyLong())).thenReturn( Arrays.asList(new OrganizationRole( OrganizationRoleType.SUPPLIER))); supplierShareAssembler = spy(new SupplierShareResultAssembler( billingRetrievalService)); createBillingResults(); mockOrganizationData(); mockOrganizationHistoryRoles(); mockGetMarketplaceRevenueSharePercentage(); mockGetOperatorRevenueSharePercentage(); mockGetSellerRevenueSharePercentage(); mockGetProductHistoryData(); mockGetSubscriptionHistoryData(); mockGetBillingResults(); mockFindMarketplaceHistory(); mockGetOrgData(CUSTOMER); mockXmlSearch(); datatypeFactory = DatatypeFactory.newInstance(); }
void setPeriod(long periodStartTime, long periodEndTime) throws DatatypeConfigurationException { this.periodEndTime = periodEndTime; Period period = new Period(); DatatypeFactory df = DatatypeFactory.newInstance(); GregorianCalendar gc = new GregorianCalendar(); // start date period.setStartDate(BigInteger.valueOf(periodStartTime)); gc.setTimeInMillis(periodStartTime); period.setStartDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); // end date period.setEndDate(BigInteger.valueOf(periodEndTime)); gc.setTimeInMillis(periodEndTime); period.setEndDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); result.setPeriod(period); }
void setPeriod(long periodStartTime, long periodEndTime) throws DatatypeConfigurationException { this.periodStartTime = periodStartTime; this.periodEndTime = periodEndTime; Period period = new Period(); DatatypeFactory df = DatatypeFactory.newInstance(); GregorianCalendar gc = new GregorianCalendar(); // start date period.setStartDate(BigInteger.valueOf(periodStartTime)); gc.setTimeInMillis(periodStartTime); period.setStartDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); // end date period.setEndDate(BigInteger.valueOf(periodEndTime)); gc.setTimeInMillis(periodEndTime); period.setEndDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); result.setPeriod(period); }
private Period preparePeriod(long periodStartTime, long periodEndTime) throws DatatypeConfigurationException { Period period = new Period(); DatatypeFactory df = DatatypeFactory.newInstance(); GregorianCalendar gc = new GregorianCalendar(); period.setStartDate(BigInteger.valueOf(periodStartTime)); gc.setTimeInMillis(periodStartTime); period.setStartDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); period.setEndDate(BigInteger.valueOf(periodEndTime)); gc.setTimeInMillis(periodEndTime); period.setEndDateIsoFormat(df.newXMLGregorianCalendar(gc).normalize()); return period; }
public XMLGregorianCalendar toXMLCalendar(Date d) throws Exception { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(d); XMLGregorianCalendar xml = DatatypeFactory.newInstance() .newXMLGregorianCalendar(); xml.setYear(gc.get(Calendar.YEAR)); xml.setMonth(gc.get(Calendar.MONTH) + 1); xml.setDay(gc.get(Calendar.DAY_OF_MONTH)); xml.setHour(gc.get(Calendar.HOUR_OF_DAY)); xml.setMinute(gc.get(Calendar.MINUTE)); xml.setSecond(gc.get(Calendar.SECOND)); return xml; }
public static DatatypeFactory getDatatypeFactory() { ClassLoader tccl = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); DatatypeFactory df = DF_CACHE.get(tccl); if (df == null) { synchronized (DatatypeConverterImpl.class) { df = DF_CACHE.get(tccl); if (df == null) { // to prevent multiple initialization try { df = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { throw new Error(Messages.FAILED_TO_INITIALE_DATATYPE_FACTORY.format(),e); } DF_CACHE.put(tccl, df); } } } return df; }
private void vulStuurgegevens(final VrijBericht vrijBericht, final VrijBerichtStuurVrijBericht verzoek, final PartijCode zendendePartij) throws DatatypeConfigurationException { final GroepBerichtStuurgegevens stuurgegevens = objectFactory.createGroepBerichtStuurgegevens(); stuurgegevens.setCommunicatieID(UUID.randomUUID().toString()); final SysteemNaam zendendeSysteem = new SysteemNaam(); final Referentienummer referentieNummer = new Referentienummer(); final DatumTijd tijdstipVerzending = new DatumTijd(); zendendeSysteem.setValue("BRP"); referentieNummer.setValue(UUID.randomUUID().toString()); final GregorianCalendar c = new GregorianCalendar(); final XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); c.setTime(vrijBericht.getTijdstipRegistratie()); tijdstipVerzending.setValue(xmlDate); stuurgegevens.setZendendePartij(objectFactory.createGroepBerichtStuurgegevensZendendePartij(zendendePartij)); stuurgegevens.setZendendeSysteem(objectFactory.createGroepBerichtStuurgegevensZendendeSysteem(zendendeSysteem)); stuurgegevens.setReferentienummer(objectFactory.createGroepBerichtStuurgegevensReferentienummer(referentieNummer)); stuurgegevens.setTijdstipVerzending(objectFactory.createGroepBerichtStuurgegevensTijdstipVerzending(tijdstipVerzending)); verzoek.setStuurgegevens(objectFactory.createObjecttypeBerichtStuurgegevens(stuurgegevens)); }
private static void test(int offsetMinutes) throws DatatypeConfigurationException { XMLGregorianCalendar calendar = DatatypeFactory.newInstance(). newXMLGregorianCalendar(); calendar.setTimezone(60 + offsetMinutes); TimeZone timeZone = calendar.getTimeZone(DatatypeConstants.FIELD_UNDEFINED); String expected = (offsetMinutes < 10 ? "GMT+01:0" : "GMT+01:") + offsetMinutes; if (!timeZone.getID().equals(expected)) { throw new RuntimeException("Test failed: expected timezone: " + expected + " Actual: " + timeZone.getID()); } }
/** * main method. * * @param args Standard args. */ public static void main(String[] args) { try { String dateTimeString = "2006-11-22T00:00:00.0+01:02"; DatatypeFactory dtf = DatatypeFactory.newInstance(); XMLGregorianCalendar cal = dtf.newXMLGregorianCalendar( dateTimeString ); System.out.println( "XMLGregCal:" + cal.toString() ); System.out.println( "GregCal:" + cal.toGregorianCalendar() ); String toGCal = cal.toGregorianCalendar().toString(); if (toGCal.indexOf("GMT+12:00") > -1) { throw new RuntimeException("Expected GMT+01:02"); } } catch (DatatypeConfigurationException ex) { throw new RuntimeException(ex.getMessage()); } }
/** * main method. * * @param args Standard args. */ public static void main(String[] args) { try { String dateTimeString = "0001-01-01T00:00:00.0000000-05:00"; DatatypeFactory dtf = DatatypeFactory.newInstance(); XMLGregorianCalendar cal = dtf.newXMLGregorianCalendar( dateTimeString ); System.out.println( "Expected: 0001-01-01T00:00:00.0000000-05:00"); System.out.println( "Actual:" + cal.toString() ); System.out.println( "toXMLFormat:" + cal.toXMLFormat() ); String test = cal.toString(); if (test.indexOf("E-7") > -1) { throw new RuntimeException("Expected: 0001-01-01T00:00:00.0000000-05:00"); } } catch (DatatypeConfigurationException ex) { throw new RuntimeException(ex.getMessage()); } }
@Test public void testFactoryFind() throws Exception { DatatypeFactory factory = DatatypeFactory.newInstance(); Assert.assertTrue(factory.getClass().getClassLoader() == null); runWithAllPerm(() -> Thread.currentThread().setContextClassLoader(null)); factory = DatatypeFactory.newInstance(); Assert.assertTrue(factory.getClass().getClassLoader() == null); runWithAllPerm(() -> Thread.currentThread().setContextClassLoader(new MyClassLoader())); factory = DatatypeFactory.newInstance(); if (System.getSecurityManager() == null) Assert.assertTrue(myClassLoaderUsed); else Assert.assertFalse(myClassLoaderUsed); }
@Test public void testDurationSubtract() { try { Duration bigDur = DatatypeFactory.newInstance().newDuration(20000); Duration smallDur = DatatypeFactory.newInstance().newDuration(10000); if (smallDur.subtract(bigDur).getSign() != -1) { Assert.fail("smallDur.subtract(bigDur).getSign() is not -1"); } if (bigDur.subtract(smallDur).getSign() != 1) { Assert.fail("bigDur.subtract(smallDur).getSign() is not 1"); } if (smallDur.subtract(smallDur).getSign() != 0) { Assert.fail("smallDur.subtract(smallDur).getSign() is not 0"); } } catch (DatatypeConfigurationException e) { e.printStackTrace(); } }
@Test public void testDurationMultiply() { int num = 5000; // millisends. 5 seconds int factor = 2; try { Duration dur = DatatypeFactory.newInstance().newDuration(num); if (dur.multiply(factor).getSeconds() != 10) { Assert.fail("duration.multiply() return wrong value"); } // factor is 2*10^(-1) if (dur.multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 1) { Assert.fail("duration.multiply() return wrong value"); } if (dur.subtract(DatatypeFactory.newInstance().newDuration(1000)).multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 0) { Assert.fail("duration.multiply() return wrong value"); } } catch (DatatypeConfigurationException e) { e.printStackTrace(); } }
@Test public void testDurationAndCalendar1() { int year = 1; int month = 2; int day = 3; int hour = 4; int min = 5; int sec = 6; String lexicalRepresentation = "P" + year + "Y" + month + "M" + day + "DT" + hour + "H" + min + "M" + sec + "S"; try { Duration dur = DatatypeFactory.newInstance().newDuration(lexicalRepresentation); System.out.println(dur.toString()); AssertJUnit.assertTrue("year should be 1", dur.getYears() == year); AssertJUnit.assertTrue("month should be 2", dur.getMonths() == month); AssertJUnit.assertTrue("day should be 3", dur.getDays() == day); AssertJUnit.assertTrue("hour should be 4", dur.getHours() == hour); AssertJUnit.assertTrue("minute should be 5", dur.getMinutes() == min); AssertJUnit.assertTrue("second should be 6", dur.getSeconds() == sec); } catch (DatatypeConfigurationException e) { e.printStackTrace(); } }
@Test public void testDurationAndCalendar3() { try { Calendar cal = new GregorianCalendar(); cal.set(Calendar.SECOND, 59); DatatypeFactory.newInstance().newDuration(10000).addTo(cal); AssertJUnit.assertTrue("sec will be 9", cal.get(Calendar.SECOND) == 9); Date date = new Date(); date.setSeconds(59); DatatypeFactory.newInstance().newDuration(10000).addTo(date); AssertJUnit.assertTrue("sec will be 9", date.getSeconds() == 9); } catch (DatatypeConfigurationException e) { e.printStackTrace(); } }
public static XMLGregorianCalendar convertDateToXMLGregorianCalendar(Date date) { GregorianCalendar c = new GregorianCalendar(); c.setTime(date); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); XMLGregorianCalendar xt = null; try { xt = DatatypeFactory.newInstance().newXMLGregorianCalendar(year, month + 1, day, 0, 0, 0, 0, 0); } catch (DatatypeConfigurationException e) { e.printStackTrace(); } return xt; }
/** * Creates variables used by this class for tracking last seen messages. * m_prevIntervalTimelineMap contains the previous timeline (milliseconds from epoch time) * for each message ID. m_alreadySeen contains the message IDs of those messages that were seen * previously. * @throws AdeException */ private final void createUsageVariables() throws AdeException { String dataObjectName = getAnalysisGroup() + "." + getName() + ".m_prevIntervalTimelineMap"; Object tmp = Ade.getAde().getDataStore().models().getModelDataObject(dataObjectName); instantiateTimelineAndAlreadySeen(dataObjectName,tmp); dataObjectName = getAnalysisGroup() + "." + getName() + ".m_alreadySeen"; tmp = Ade.getAde().getDataStore().models().getModelDataObject(dataObjectName); instantiateTimelineAndAlreadySeen(dataObjectName,tmp); if (m_dataTypeFactory == null) { try { m_dataTypeFactory = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { throw new AdeInternalException("Failed to instantiate data factory for calendar", e); } } if (m_gc == null) { final TimeZone outputTimeZone = Ade.getAde().getConfigProperties().getOutputTimeZone(); m_gc = new GregorianCalendar(outputTimeZone); } }
public static XMLGregorianCalendar getFullXmlDate(String dateString) { try { Calendar calendar = GregorianCalendar.getInstance(); if (! StringUtils.isEmpty(dateString)) { DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date date = dateFormat.parse(dateString); calendar.setTime(date); } return DatatypeFactory.newInstance().newXMLGregorianCalendarDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED); } catch (Exception e) { e.printStackTrace(); return null; } }
@Test public void testFactoryFind() { try { // System.setProperty("jaxp.debug", "true"); DatatypeFactory factory = DatatypeFactory.newInstance(); Assert.assertTrue(factory.getClass().getClassLoader() == null); Thread.currentThread().setContextClassLoader(null); factory = DatatypeFactory.newInstance(); Assert.assertTrue(factory.getClass().getClassLoader() == null); Thread.currentThread().setContextClassLoader(new MyClassLoader()); factory = DatatypeFactory.newInstance(); if (System.getSecurityManager() == null) Assert.assertTrue(myClassLoaderUsed); else Assert.assertFalse(myClassLoaderUsed); } catch (Exception ex) { } }
/** * 获取UTC时间 * @return */ public static XMLGregorianCalendar getCurrentUTCTime() { Date date = new Date(); GregorianCalendar nowGregorianCalendar = new GregorianCalendar(); XMLGregorianCalendar xmlDatetime = null; try { nowGregorianCalendar.setTime(date); xmlDatetime = DatatypeFactory.newInstance() .newXMLGregorianCalendar(nowGregorianCalendar); } catch (DatatypeConfigurationException e) { LOGGER.error("", e); } return xmlDatetime; }
private static XMLGregorianCalendar map(final java.util.Date date) { XMLGregorianCalendar converted = null; if (date != null) { final GregorianCalendar calendar = new GregorianCalendar(); // Throws a NullPointerException without the null check calendar.setTime(date); try { converted = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { throw new IWSException(IWSErrors.ERROR, e.getMessage(), e); } } return converted; }
/** * 将时间转换为格林威治时间格式的字符串 * * @param date 需要格式化的时间 * @return 格式化后的时间格式 */ public static String date2GregorianFormat(Date date) { if (null == date) { return ""; } try { DatatypeFactory factory = DatatypeFactory.newInstance(); GregorianCalendar gCal = (GregorianCalendar) GregorianCalendar .getInstance(); gCal.setTime(date); String result = factory.newXMLGregorianCalendar(gCal).toString(); return result; } catch (DatatypeConfigurationException e) { LOGGER.error("date2GregorianFromatd error", e); return date.toString(); } }
/** * To get a XMLGregorianCalendar for now * @return a XMLGregorianCalendar for now * @throws DatatypeConfigurationException if it can't create a calendar */ public static XMLGregorianCalendar giveMeCalendarForNow() throws DatatypeConfigurationException { GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(new Date()); XMLGregorianCalendar result = null; DatatypeFactory factory = DatatypeFactory.newInstance(); result = factory.newXMLGregorianCalendar( gregorianCalendar.get(GregorianCalendar.YEAR), gregorianCalendar.get(GregorianCalendar.MONTH) + 1, gregorianCalendar.get(GregorianCalendar.DAY_OF_MONTH), gregorianCalendar.get(GregorianCalendar.HOUR_OF_DAY), gregorianCalendar.get(GregorianCalendar.MINUTE), gregorianCalendar.get(GregorianCalendar.SECOND), gregorianCalendar.get(GregorianCalendar.MILLISECOND), 0); return result; }
/** * 输入以分钟为单位的数据,返回duration类型数据 * * @param dur /** * @return */ public static Duration durationInt2dur(Integer dur) { Duration duration = null; try { if (0<=dur) { duration = DatatypeFactory.newInstance().newDuration("PT"+Math.abs(dur)+"M"); }else { duration = DatatypeFactory.newInstance().newDuration("-PT"+Math.abs(dur)+"M"); } } catch (DatatypeConfigurationException e) { e.printStackTrace(); } return duration; }
/** * Date类型转XMLGregorianCalendar类型 * @param date * @return 用于预约周期会议返回的情况 */ public static XMLGregorianCalendar toGregorianCalendarDateSMC(Date date) { if (null == date) { return null; } GregorianCalendar nowGregorianCalendar = new GregorianCalendar(); XMLGregorianCalendar xmlDatetime = null; try { nowGregorianCalendar.setTime(date); xmlDatetime = DatatypeFactory.newInstance() .newXMLGregorianCalendar(nowGregorianCalendar); } catch (DatatypeConfigurationException e) { LOGGER.error("", e); } return xmlDatetime; }
public static int getDuration(String id) throws IOException, JSONException, QuotaExceededException { try { String apiString = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=" + id + "&key=" + key; String response = WebUtil.getWebPage(apiString); //siteToString(new URL(apiString)); JSONObject js = new JSONObject(response); Duration dur = DatatypeFactory.newInstance().newDuration( js.getJSONArray("items").getJSONObject(0).getJSONObject("contentDetails").getString("duration")); int hours = dur.getHours(); int minutes = dur.getMinutes(); int seconds = dur.getSeconds(); int totalSeconds = (hours * 3600) + (minutes * 60) + seconds; return totalSeconds; } catch (DatatypeConfigurationException e) { e.printStackTrace(); } return -1; }
static XMLGregorianCalendar getTimeNowAsXMLGregorianCalendar() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); /* Most important. Please check your machine's/workstations/VM's time if WS-Security header error TPE1122 occurs. For unix/linux you can use ntp or run below command. sudo date -s "$(wget -qSO- --max-redirect=0 google.com 2>&1 | grep Date: | cut -d' ' -f5-8)Z" */ sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String date = sdf.format(new Date()); XMLGregorianCalendar xMLGregorianCalendar = null; try { xMLGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(date); } catch (DatatypeConfigurationException e) { LOG.error("Error: ", e); } return xMLGregorianCalendar; }
@Override public ClassLoader createFilteringClassLoader(ClassLoader parent, FilteringClassLoader.Spec spec) { // See the comment for {@link #createIsolatedClassLoader} above FilteringClassLoader.Spec classLoaderSpec = new FilteringClassLoader.Spec(spec); if (needJaxpImpl()) { makeServiceVisible(systemClassLoaderServiceLocator, classLoaderSpec, SAXParserFactory.class); makeServiceVisible(systemClassLoaderServiceLocator, classLoaderSpec, DocumentBuilderFactory.class); makeServiceVisible(systemClassLoaderServiceLocator, classLoaderSpec, DatatypeFactory.class); } return doCreateFilteringClassLoader(parent, classLoaderSpec); }
public XMLGregorianCalendar createXMLGregorianCalendar(Calendar calendar) { if (dateFactory == null) { try { dateFactory = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { throw new IllegalStateException("Could not obtain an instance of DatatypeFactory.", e); } } return dateFactory.newXMLGregorianCalendar((GregorianCalendar) calendar); }
public void test_for_issue() throws Exception { Date now = new Date(); GregorianCalendar gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance(); gregorianCalendar.setTime(now); XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); String jsonString = JSON.toJSONString(calendar); // success calendar = JSON.parseObject(jsonString, XMLGregorianCalendar.class); Object toJSON1 = JSON.toJSON(calendar); // debug看到是 Long 类型 // 所以这里会报错: // error: java.lang.ClassCastException: java.lang.Long cannot be cast to com.alibaba.fastjson.JSONObject //JSONObject jsonObject = (JSONObject) JSON.toJSON(calendar); // 所以 这里肯定会报错, 因为 jsonObject 不是JSONObject类型 //calendar = jsonObject.toJavaObject(XMLGregorianCalendar.class); List<XMLGregorianCalendar> calendarList = new ArrayList<XMLGregorianCalendar>(); calendarList.add(calendar); calendarList.add(calendar); calendarList.add(calendar); Object toJSON2 = JSON.toJSON(calendarList); // debug 看到是 JSONArray 类型 // success: 通过 JSONArray.parseArray 方法可以正确转换 JSONArray jsonArray = (JSONArray) JSON.toJSON(calendarList); jsonString = jsonArray.toJSONString(); List<XMLGregorianCalendar> calendarList1 = JSONArray.parseArray(jsonString, XMLGregorianCalendar.class); // 通过 jsonArray.toJavaList 无法转换 // error: com.alibaba.fastjson.JSONException: can not cast to : javax.xml.datatype.XMLGregorianCalendar List<XMLGregorianCalendar> calendarList2 = jsonArray.toJavaList(XMLGregorianCalendar.class); assertNotNull(calendarList2); assertEquals(3, calendarList2.size()); }