就像标题所说的那样,我试图为我已定义的类包含其他类别I类所定义的对象的对象编写自定义解码器。 "外部" class是一个Edge,定义如下:
class Edge:
def __init__(self, actor, movie):
self.actor = actor
self.movie = movie
def __eq__(self, other):
if (self.movie == other.movie) & (self.actor == other.actor):
return True
else:
return False
def __str__(self):
print("Actor: ", self.actor, " Movie: ", self.movie)
def get_actor(self):
return self.actor
def get_movie(self):
return self.movie
使用"内部"类actor和电影定义如下:
class Movie:
def __init__(self, title, gross, soup, year):
self.title = title
self.gross = gross
self.soup = soup
self.year = year
def __eq__(self, other):
if self.title == other.title:
return True
else:
return False
def __repr__(self):
return self.title
def __str__(self):
return self.title
def get_gross(self):
return self.gross
def get_soup(self):
return self.soup
def get_title(self):
return self.title
def get_year(self):
return self.year
class Actor:
def __init__(self, name, age, soup):
self.name = name
self.age = age
self.soup = soup
def __eq__(self, other):
if self.name == other.name:
return True
else:
return False
def __repr__(self):
return self.name
def __str__(self):
return self.name
def get_age(self):
return self.age
def get_name(self):
return self.name
def get_soup(self):
return self.soup
(汤只是该电影/演员维基百科页面的美丽对象,可以忽略不计)。 我也为边缘类编写了一个客户编码器:
class EdgeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Edge):
return {
"Actor": {
"Name": o.get_actor().get_name(),
"Age": o.get_actor().get_age()
},
"Movie": {
"Title": o.get_movie().get_title(),
"Gross": o.get_movie().get_gross(),
"Year": o.get_movie().get_year()
}
}
return json.JSONEncoder.default(self, o)
我已经测试过,它正确地将边列表序列化为JSON文件。现在我的问题出现在尝试编写边缘解码器时。我已经使用github页面here作为参考,但我的编码器偏离了他,我想知道是否需要更改它。我是否需要在其JSON序列化中将对象的类型显式编码为其自己的键值对,或者是否有某种方法可以获取" Actor"和"电影"键的边缘序列化?同样,有没有办法抓住" Name"。 " Age"等,这样我可以重建Actor / Movie对象,然后使用它们重建边缘?有没有更好的方法来编码我的对象?我也尝试过this教程,但是我发现对象的使用会让编码器感到困惑,而且我不确定如何将该方法扩展到包含自定义对象的自定义对象。
答案 0 :(得分:0)
您引用的编码器/解码器示例(here)可以轻松扩展,以允许JSON输入/输出中使用不同类型的对象。
但是,如果您只希望一个简单的解码器与您的编码器匹配(仅将Edge对象编码在JSON文件中),请使用以下解码器:
class EdgeDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, dct):
if 'Actor' in dct:
actor = Actor(dct['Actor']['Name'], dct['Actor']['Age'], '')
movie = Movie(dct['Movie']['Title'], dct['Movie']['Gross'], '', dct['Movie']['Year'])
return Edge(actor, movie)
return dct
使用问题中的代码定义类Movie
,Actor
,Edge
和EdgeEncoder
,以下代码将输出测试文件,然后将其读回在:
filename='test.json'
movie = Movie('Python', 'many dollars', '', '2000')
actor = Actor('Casper Van Dien', 49, '')
edge = Edge(actor, movie)
with open(filename, 'w') as jsonfile:
json.dump(edge, jsonfile, cls=EdgeEncoder)
with open(filename, 'r') as jsonfile:
edge1 = json.load(jsonfile, cls=EdgeDecoder)
assert edge1 == edge
答案 1 :(得分:-1)
无需使用JSONEncoder
或JSONDecoder
即可解决此问题。
to_dict()
方法(负责从python object
到JSON dict
的转换)bool, str, int, and float
以外的参数类型,请检查传递的参数是否为dict
类型,如果是这种情况,则必须自己构造该对象(请参见{{ 1}})简化了您的示例:
Edge
返回:
class Edge:
def __init__(self, actor, movie):
if type(actor) is Actor:
self.actor = actor
else: # type == dict
self.actor = Actor(**actor)
if type(movie) is Movie:
self.movie = movie
else: # type == dict
self.movie = Movie(**movie)
def __eq__(self, other):
return (self.movie == other.movie) & (self.actor == other.actor)
def __str__(self):
return "".join(["Actor: ", str(self.actor), " /// Movie: ", str(self.movie)])
def to_dict(self):
return {"actor": self.actor.to_dict(), "movie": self.movie.to_dict()}
class Movie:
def __init__(self, title, gross, soup, year):
self.title = title
self.gross = gross
self.soup = soup
self.year = year
def __eq__(self, other):
return self.title == other.title
def __str__(self):
return self.title
def to_dict(self):
return {"title": self.title, "gross": self.gross, "soup": self.soup, "year": self.year}
class Actor:
def __init__(self, name, age, soup):
self.name = name
self.age = age
self.soup = soup
def __eq__(self, other):
return self.name == other.name
def __str__(self):
return self.name
def to_dict(self):
return {"name": self.name, "age": self.age, "soup": self.soup}
if __name__ == '__main__':
edge_obj = Edge(Actor("Pierfrancesco Favino", 50, "id0"), Movie("Suburra", 10, "id1", 2015))
edge_dict = edge_obj.to_dict()
edge_obj_new = Edge(**edge_dict)
print("manual edge\t\t", edge_obj)
print("edge to json\t", edge_dict)
print("auto edge\t\t", edge_obj_new)
print("edges equal?\t", edge_obj == edge_obj_new)
您会看到两个manual edge Actor: Pierfrancesco Favino /// Movie: Suburra
edge to json {'actor': {'name': 'Pierfrancesco Favino', 'age': 50, 'soup': 'id0'}, 'movie': {'title': 'Suburra', 'gross': 10, 'soup': 'id1', 'year': 2015}}
auto edge Actor: Pierfrancesco Favino /// Movie: Suburra
edges equal? True
对象相等,第二行以Edge
表示形式将Edge
输出为dict
。