Closed ngiachou closed 6 years ago
Now PesonalBank
objects are json-serializable.
Testing output:
{
"name": "Beer",
"price": 2.5
}
{
"date": "2018-10-29",
"environment characteristic": "friends",
"place": "in",
"product list": [
{
"name": "Beer",
"price": 2.5
},
{
"name": "Pizza",
"price": 9.0
}
]
}
{
"balance": 350,
"history": [
{
"date": "2018-10-29",
"environment characteristic": "friends",
"place": "in",
"product list": [
{
"name": "Beer",
"price": 2.5
},
{
"name": "Pizza",
"price": 9.0
}
]
}
]
}
OK, so I've made two encoders actually. One works for Product instances and the other for Transaction instancies. There will be another encoder for PersonalBank instances when that class is implemented.
Essentially, the implementation calls the encoder of the top level and recursively calling encoders for lower level. For example, to encode a Transaction instance the encoder for that instance is called which in turn calls the encoder for every product in the product list.
Here is the testing code:
and here is the response:
notice that both
json.loads()
andjson.dumps()
are called. The former is for reading json strings and the latter for creating them. Hence, the whole cycle of read/write works. There is a catch though...Loading a json string just makes it a dictionary which means that we still have to convert that into instances of the specific classes.