I am having a problem I can't quite seem to find the solution to. I have an application that speaks with a Java app via JSON. Pretty simple, but I'm having an issue decoding JSON off the wire with nested objects. For example I have:
class obj1(object):
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
def __eq__(self, other):
return (isinstance(other, obj1) and
self.var1 == obj1.var1 and
self.var2 == obj2.var2)
class obj2(object):
def __init__(self, v1, v2, obj1):
self.v1 = v1
self.v2 = v2
self.obj1 = obj1
and I want to serialize and de-serialize the "obj2" class, I can create it pretty easily:
myObj1 = obj1(1,2)
myObj2 = obj2(3.14, 10.05, myObj1)
when I want to send it Json, it's obviously pretty easy:
import json
def obj_to_dict(obj):
return obj.__dict__
my_json = json.dumps(myObj2, default=obj_to_dict)
this creates the perfect JSON as I would expect:
{"obj1": {"var1": 1, "var2": 2}, "v1": 3.14, "v2": 10.05}
the problem I am having is encoding this string back into the two objects. I can't add any extra type information because the application that sends this schema back sends it back in exactly this way. so when I try and rebuild it from the dictionary:
obj_dict = json.loads(my_json)
myNewObj = obj2(**obj_dict)
it doesn't quite work
print myNewObj.obj1 == obj1 #returns False.
Is there some better way to get from JSON -> Custom objects? (In reality I have like 20 custom objects nested inside another Object. the Object -> JSON works perfectly, its just going the other direction. Any thoughts?