简体   繁体   English

序列化自定义对象列表

[英]Serialize a list of custom objects

I am creating an list of custom objects from a database. 我正在从数据库创建自定义对象列表。 The custom object class and the list creation is shown below. 自定义对象类和列表创建如下所示。 How can I serialize the list holding this custom data? 如何序列化保存此自定义数据的列表?

class MyCustomObject():
    """For displaying the records"""
    def __init__(self):
        self.rec_id = ""
        self.place = ""

rec_list = [] #The List
# Creating a list of MyCustomObject's from rows
for col in rows:
    rec = MyCustomObject()            
    rec.rec_id = col[0]
    rec.place = col[1]
    rec_list.append(recently_viewed)

How can I serialize this list of MyCustomObject s to JSON. 如何将此MyCustomObject列表序列化为JSON。

you could try writing your own serializer as below: 您可以尝试编写自己的序列化程序,如下所示:

import json

class MyCustomObject():
    """For displaying the records"""
    def __init__(self):
        self.rec_id = ""
        self.place = ""

class mySerializer(json.JSONEncoder):
    def default(self, obj):
        return obj.__dict__

rec_list = [] #The List
# Creating a list of MyCustomObject's from rows
rows = [[1,2],[3,4]]
for col in rows:
    rec = MyCustomObject()            
    rec.rec_id = col[0]
    rec.place = col[1]
    rec_list.append(rec)

print [json.dumps(r, cls=mySerializer)  for r in rec_list]

output: 输出:

 ['{"place": 2, "rec_id": 1}', '{"place": 4, "rec_id": 3}']

By extending JsonEncoder ( https://docs.python.org/2/library/json.html#json.JSONEncoder ) 通过扩展JsonEncoder( https://docs.python.org/2/library/json.html#json.JSONEncoder

So you will get something like; 所以你会得到类似的东西;

import json

class MyJsonEncoder
    def default(self, obj):
        if isinstance(obj, MyCustomObject):
            return {}  # dict representation of your object
        return super(MyJsonEncoder, self).dumps(obj)

json.dumps(rec_list, encoder=MyJsonEncoder)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM