[json-lib-user] Converting GregorianCalendar object, Java to JSON and back
Brought to you by:
aalmiray
From: Darlene W. <dar...@gm...> - 2008-06-06 22:08:33
|
Hi, I'm new to json-lib. I want to convert a Java class into JSONObject and then back again. I am able to do this conversion with a Date class. However, the class I want to convert contains a nested XMLGregorianCalendar object, which has issues when converting from JSONObject to Java. I've tried to create a simple test case that converts only a GregorianCalendar object ( http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html). This works fine when converting from Java to JSONObject, but the reverse conversion gives an InstantiationException error when calling toJava(). Here is my sample code: GregorianCalendar gc = DateUtil.getCalendar(-7); System.out.println(gc.toString()); // Convert object to JSON JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(gc); System.out.println(jsonObject.toString()); // Convert JSON object back into Java object GregorianCalendar gc2; JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setRootClass(GregorianCalendar.class); gc2 = (GregorianCalendar) JSONSerializer.toJava(jsonObject, jsonConfig); System.out.println(gc2.toString()); The output is as follows: java.util.GregorianCalendar[time=1212788878236,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=java.util.SimpleTimeZone[id=GMT-07:00,offset=-25200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=3,startDay=1,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=7200000,endTimeMode=0],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2008,MONTH=5,WEEK_OF_YEAR=23,WEEK_OF_MONTH=1,DAY_OF_MONTH=6,DAY_OF_YEAR=158,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=47,SECOND=58,MILLISECOND=236,ZONE_OFFSET=-25200000,DST_OFFSET=3600000] {"firstDayOfWeek":1,"gregorianChange":{"date":4,"day":4,"hours":16,"minutes":0,"month":9,"seconds":0,"time":-12219292800000,"timezoneOffset":480,"year":-318},"lenient":true,"minimalDaysInFirstWeek":1,"time":{"date":6,"day":5,"hours":14,"minutes":47,"month":5,"seconds":58,"time":1212788878236,"timezoneOffset":420,"year":108},"timeInMillis":1212788878236,"timeZone":{"DSTSavings":3600000,"ID":"GMT-07:00","displayName":"GMT-07:00","rawOffset":-25200000}} net.sf.json.JSONException: java.lang.InstantiationException at net.sf.json.JSONObject.toBean(JSONObject.java:304) at net.sf.json.JSONObject.toBean(JSONObject.java:420) at net.sf.json.JSONSerializer.toJava(JSONSerializer.java:69) ... Like I said, I am able to get the same code to work on other objects, such as Date objects, so what am I missing? Is there a limitation on the types of objects that can be converted to JSONObject and back? Any help or pointers is greatly appreciated! Darlene |