【问题标题】:JSON - Encoding a List of Serializable ObjectsJSON - 对可序列化对象列表进行编码
【发布时间】:2020-11-05 14:04:34
【问题描述】:

我有以下代码。本质上,有两个类 - 乐高主题,它充当乐高主题对象的容器。我已经实现了一个方法“saveThemes()”,它基本上遍历主题 - 将单独存储的乐高对象转换为 JSON,然后将它们添加到变量 (resultantJson)。

但是,我很欣赏这有点“黑客”。我应该能够直接执行 self__.themes 的 json.dumps() 吗(它目前说该对象是可序列化的)?

import json


class LegoThemes:
    def __init__(self):
        self.__themes = []

    def saveThemes(self):
        resultantJson = ""

        for theme in self.__themes:
            resultantJson += json.dumps(theme.__dict__)

        # TODO: Output resultantJSON to .JSON file.
        return resultantJson

    # TODO: implement loadThemes(self)

    def addTheme(self, theme):
        self.__themes.append(theme)


class LegoTheme:
    def __init__(self, title, description, thumbnailImage, logoImage, url):
        self.__title = title
        self.__description = description
        self.__thumbnailImage = thumbnailImage
        self.__logoImage = logoImage
        self.__url = url

    def getTitle(self):
        return self.__title


testThemeOne = LegoTheme(
    "Test Theme One Title",
    "Test Theme One Description.",
    "Test Theme One Thumbnail Image",
    "Test Theme One Logo Image",
    "Test Theme One URL",
)

testThemeTwo = LegoTheme(
    "Test Theme Two Title",
    "Test Theme Two Description.",
    "Test Theme Two Thumbnail Image",
    "Test Theme Two Logo Image",
    "Test Theme Two URL",
)

testThemeThree = LegoTheme(
    "Test Theme Three Title",
    "Test Theme Three Description.",
    "Test Theme Three Thumbnail Image",
    "Test Theme Three Logo Image",
    "Test Theme Three URL",
)

legoThemes = LegoThemes()

legoThemes.addTheme(testThemeOne)
legoThemes.addTheme(testThemeTwo)
legoThemes.addTheme(testThemeThree)

print(legoThemes.saveThemes())

【问题讨论】:

  • 顺便说一句,从saveThemes() 返回的字符串在技术上是不是 json。
  • @quamrana 因为它们没有封装在一个 JSON“字符串”中?
  • 如果您查看website,则唯一允许的顶级对象是列表[] 或对象{}。您必须问自己,您希望 json 解码 saveThemes() 的结果会产生什么?
  • @quamrana 很好,谢谢你完全理解。

标签: python json class object


【解决方案1】:

您可以将__dict__ 成员的列表转换为json

    def saveJson(self):
        return json.dumps([t.__dict__ for t in self.__themes])

【讨论】:

    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2013-08-30
    • 2013-01-31
    • 2011-03-18
    相关资源
    最近更新 更多