Parsing Serialized Java objects in Python
Question: The string at the bottom of this post is the serialization of a
`java.util.GregorianCalendar` object in Java. I am hoping to parse it in
Python.

I figured I could approach this problem with a combination of regexps and
`key=val` splitting, i.e. something along the lines of:

`text_inside_brackets = re.search(r"\[(.*)\]", text).group(1)`

and

    
    
    import parse
    for x in [parse('{key} = {value}', x) for x in  text_inside_brackets.split('=')]:
     my_dict[x['key']] = x['value'] 
    

My question is: What would be a more **principled** / **robust** approach to
do this? Are there any Python parsers for serialized Java objects that I could
use for this problem? (do such things exist?). What other alternatives do I
have?

My hope is to ultimately parse this in JSON or nested Python dictionaries, so
that I can manipulate it it any way I want.

**Note:** I would prefer to avoid a solution relies on
[Py4J](http://py4j.sourceforge.net/) mostly because it requires setting up a
server and a client, and I am hoping to do this within a single Python script.

>
> `java.util.GregorianCalendar[time=1413172803113,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=9,WEEK_OF_YEAR=42,WEEK_OF_MONTH=3,DAY_OF_MONTH=13,DAY_OF_YEAR=286,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=3,MILLISECOND=113,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]`


Answer: The serialized form of a GregorianCalendar object contains quite a lot of
redundancy. In fact, there are only two fields that matter, if you want to
reconstitute it:

  1. the time
  2. the timezone

There is code for extracting this in [How to Convert Gregorian String to
Gregorian Calendar](http://stackoverflow.com/questions/25807422/how-to-
convert-gregorian-string-to-gregorian-calendar/25809374#25809374)

If you want a more principled and robust approach, I echo mbatchkarov's
suggestion to use JSON.

