Junior — Middle
How can serialization be used to build a data model?
sobes.tech AI
Answer from AI
Serialization method allows converting a data model object into a format suitable for storage or transmission (e.g., JSON, XML, or byte stream). This is convenient for building data models, as you can define the structure of the object and then easily save and restore its state.
For example, in Python, you can serialize a dictionary representing a model using the json module:
import json
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def to_dict(self):
return {'name': self.name, 'age': self.age}
user = User('Ivan', 30)
serialized = json.dumps(user.to_dict(), ensure_ascii=False)
print(serialized) # {"name": "Ivan", "age": 30}
Thus, serialization helps in building models that are easy to save, transmit, and restore.