簡體   English   中英

序列化自定義對象列表

[英]Serialize a list of custom objects

我正在從數據庫創建自定義對象列表。 自定義對象類和列表創建如下所示。 如何序列化保存此自定義數據的列表?

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)

如何將此MyCustomObject列表序列化為JSON。

您可以嘗試編寫自己的序列化程序,如下所示:

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]

輸出:

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

通過擴展JsonEncoder( https://docs.python.org/2/library/json.html#json.JSONEncoder

所以你會得到類似的東西;

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