Skip to content

How to remap field names? #9

@kitschen

Description

@kitschen

I receive JSON with a datetime field called from. As from is a keyword in Python, I cannot create a dataclass with a from field. So deserialization is not possible.

Is there any way of mapping the JSON's from to a different Python field name?

Example test case (which currently fails):

import json
from dataclasses import dataclass
from unittest import TestCase

from dataclasses_serialization.json import JSONSerializer


@dataclass(frozen=True)
class TimeRangeDTO:
    from_dt: int
    to_dt: int


class TestTimeRangeDTO(TestCase):
    testJson = r"""{
"from": 1589087316000,
"to": 1589173716000
}"""

    def testTimeRangeDTODeserialization(self):
        # Expected to map the JSON's "from" property to the Python class' "from_dt" property
        x: TimeRangeDTO = JSONSerializer.deserialize(TimeRangeDTO, json.loads(self.testJson))
        self.assertEqual(1589087316000, x.from_dt)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions