Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deserialization with jsons to nested classes #188

Open
t-raww187 opened this issue May 18, 2023 · 1 comment
Open

deserialization with jsons to nested classes #188

t-raww187 opened this issue May 18, 2023 · 1 comment

Comments

@t-raww187
Copy link

Hello,
It is not very clear to me how to deserialize a json for nested classes. Let's say we have the following classes

import jsons
from typing import List, Tuple, Dict
class Person:
    def __init__(self):
        self.name = ''
        self.age = ''
        self.address= Address()
        
class Address:
    def __init__(self):
        self.street= ''
        self.cp = ''

p = Person()
d = Address()

j = {'name': 'John', 'age': '30', 'address': {'street': '41 Ave', 'cp': '08019'}}

obj = jsons.load(j, Person)

print(obj.address)
>>>{'street': '41 Ave', 'cp': '08019'}

Does not return an Address object.
Any way to solve this silly problem?
thanks in advance

@bedapisl
Copy link

Hello, I think you need to have all parameters in the constructor. And these parameters need type hints. After these changes it works for me:

import jsons
from typing import List, Tuple, Dict


class Address:
    def __init__(self, street: str='', cp: str=''):
        self.street = street
        self.cp = cp


class Person:
    def __init__(self, name: str='', age: int='', address: Address=Address()):
        self.name = name
        self.age = age
        self.address = address


p = Person()
d = Address()

j = {'name': 'John', 'age': '30', 'address': {'street': '41 Ave', 'cp': '08019'}}

obj = jsons.load(j, Person)

print(obj.address)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants