本文介绍了当反序列化没有jsonpickle元数据/类型信息的json时,如何告诉jsonpickle创建哪个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,但是在其他语言中,我已经能够告诉序列化程序我要创建哪种类型,并允许它基于反射/自省反序列化或绑定属性.

I'm new to python but in other languages I have been able to tell a serializer what type I want created and let it deserialize or bind the properties based on reflection/introspection.

jsonpickle如果使用jsonpickle进行序列化,则会将类型信息添加到json,但是在这种情况下,我获取的json来自外部来源,并且其中没有类型元数据.

jsonpickle adds type information to the json if you serialize it with jsonpickle, however in this case the json I am getting comes from an external source and does not have the type metadata in it.

我只想将类型信息传递给序列化器.

I would like to just pass the type information to a serializer.

import jsonpickle

class TestObject(object):

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

#from an external source
jsons = '{ "name" : "Test" }'

我希望我可以做类似的事情:

I would expect I could just do something like:

jsonpickle.decode(jsons,TestObject)

这是我的问题的C#示例: http://james.newtonking.com/json/help /index.html?topic=html/M_Newtonsoft_Json_JsonConvert_DeserializeObject_3.htm

Here is a C# example of my question:http://james.newtonking.com/json/help/index.html?topic=html/M_Newtonsoft_Json_JsonConvert_DeserializeObject_3.htm

C#看起来像:

public class TestObject {
    public string Name { get;set; }
}

var json = "{ "name" : "Test" }";

var deserialized = JsonConvert.DeserializeObject(json,typeof(TestObject));

我知道没有键入python等信息,但是没有理由为什么我只需要为基本的序列化而搞乱字典映射.

I know python is not typed, etc ... but there is no reason why I should need to be messing around with dictionary maps just to do basic serialization.

推荐答案

首先,您提供的示例json输出不是jsonpickle将输出的内容.相反,您定义的TestObject的编码实例看起来像这样:

First of all the example json output you provided is not what jsonpickle will output. Instead an encoded instance of the TestObject you defined would look like this:

'{"py/object": "__main__.TestObject", "_name": 4}'

请注意,类型与实例变量一起被编码.解码后的输出将神奇地恢复为原始类型:

Note that the type is encoded along with the instance variables. The decoded output will magically be put back into its original type:

jsonpickle.decode('{"py/object": "__main__.TestObject", "_name": 4}')

将是一个TestObject实例.

will be a TestObject instance.

这篇关于当反序列化没有jsonpickle元数据/类型信息的json时,如何告诉jsonpickle创建哪个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 10:58