无法使用jsonpickle将json字符串解码为python对象

无法使用jsonpickle将json字符串解码为python对象,python,json,deserialization,jsonpickle,Python,Json,Deserialization,Jsonpickle,我的班级结构如下- class HelloWorld (object): def __init__(self, name, i, id): self.name = name self.i = i self.id = id 我正在创建一个对象 p = HelloWorld('pj', 3456, '1234') 将这个对象传递给一个定义,在这里我使用jsonpickle.encode和jsonpickle.decode,如下所示 >

我的班级结构如下-

class HelloWorld (object):
    def __init__(self, name, i, id):
        self.name = name
        self.i = i
        self.id = id
我正在创建一个对象

p = HelloWorld('pj', 3456, '1234')
将这个对象传递给一个定义,在这里我使用
jsonpickle.encode
jsonpickle.decode
,如下所示

>>>print(type(p)) 
    <class 'HelloWorld'>
 >>>x = jsonpickle.encode(p)        
 >>>print(x)
    {"i": 3456, "name": "pj", "py/object": "__builtin__.HelloWorld", "id": "1234"}
 >>>y = jsonpickle.decode(x)
 >>>print(type(y))
    <class 'dict'>

这里的主要问题是,该类在解码时不可用,因此无法将其解码为python对象

根据JsonPickle documentation(),对象必须可以通过模块全局访问,并且必须从对象(也称为新样式类)继承


因此,遵循以下配方。使用它,您可以生成动态模块并动态加载类。通过这种方式,在解码类时可以访问该类,因此您可以将其解码回python对象。

您是在交互式控制台中完成这一切,还是从文件导入了
HelloWorld
?我在python 2.7.7上尝试了这一点,并且使用您发布的代码可以正常工作。您可以检查您正在使用的python版本吗?也许这就是原因。我无法重现您的问题。我正在模块内自动生成此类。当我专门从交互式控制台中的.py文件加载这个类时,我无法重现这个问题。但这似乎有些不同。我将看到“py/object”的值,它的名称空间是
\uuu内置的\uuu.HelloWorld
。当我从外部加载它时,它会显示
\uuuu main\uuuu.HelloWorld
。生成类的代码是-
eval(类代码,{“object”:object},fakeglobals)
。。该类是在尝试jsonpickle.decode()时定义的,还是仅在编码时动态定义的?
def _create_pojo(self, pojo_class_name, param_schema):

    #extracting the properties from the parameter 'schema'        
    pojo_properties = param_schema['properties']

    #creating a list of property keys
    pojo_property_list = []
    for key in pojo_properties:
        pojo_property_list.append(key)

    source = \
        "class %s (object):\n" % ( pojo_class_name )       
    source += "    def __init__(self, %s" % ', '.join(pojo_property_list) +"):\n" #defining __init__ for the class
    for prop in pojo_property_list: #creating a variable in the __init__ method for each property in the property list
        source += "        self.%s = %s\n" % (prop, prop)

    #generating the class code
    class_code = compile( source, "<generated class>", "exec" )
    fakeglobals = {}
    eval( class_code, {"object" : object}, fakeglobals )
    result = fakeglobals[ pojo_class_name ]        
    result ._source = source
    pprint.pprint(source)       

    self._object_types[ pojo_class_name ] = result
    return result