0

I am getting Data via a REST-Interface and I want to store those data in a class-object.

my class could looks like this:

class Foo:
    firstname = ''
    lastname = ''
    street = ''
    number = ''

and the json may look like this:

[
    {
        "fname": "Carl",
        "lname": "any name",
        "address": ['carls street', 12]
    }
]

What's the easiest way to map between the json and my class?

My problem is: I want to have a class with a different structure than the json. I want the names of the attributes to be more meaningful.

Of course I know that I could simply write a to_json method and a from_json method which does what I want. The thing is: I have a lot of those classes and I am looking for more declarative way to write the code.

e.g. in Java I probably would use mapstruct.

Thanks for your help!

Sanjay SS
  • 568
  • 4
  • 14
maku
  • 11
  • 2
  • Does this answer your question? https://stackoverflow.com/questions/5943425/is-there-a-data-type-in-python-similar-to-structs-in-c – Ronald Jul 07 '20 at 10:37

3 Answers3

1

Use a dict for the json input. Use **kwargs in an __init__ method in your class and map the variables accordingly.

quamrana
  • 37,849
  • 12
  • 53
  • 71
0

I had a similar problem, and I solved it by using @classmethod

import json

class Robot():
    def __init__(self, x, y):
        self.type = "new-robot"
        self.x = x 
        self.y = y 

    @classmethod
    def create_robot(cls, sdict):
        if sdict["type"] == "new-robot":
            position = sdict["position"]
            return cls(position['x'], position['y'])
        else:
            raise Exception ("Unable to create a new robot!!!")    
        
if __name__=='__main__':
    input_string = '{"type": "new-robot", "position": {"x": 3, "y": 3}}'
    cmd = json.loads(input_string)
    bot = Robot.create_robot(cmd)
    print(bot.type)
alv2017
  • 752
  • 5
  • 14
0

Perhaps you could you two classes, one directly aligned with the Json (your source class) and the other having the actual structure you need. Then you could map them using the ObjectMapper class[https://pypi.org/project/object-mapper/]. This is very close to the MapStruct Library for Java. ObjectMapper is a class for automatic object mapping. It helps you to create objects between project layers (data layer, service layer, view) in a simple, transparent way.