Can I deserialize Json to class like C# Newtonsoft in Python

∥☆過路亽.° 提交于 2021-01-04 05:51:55

问题


This is json

{"name":"david","age":14,"gender":"male"}

This is python class

class Person:
    def __init__(self):
        self.name = None
        self.age = None
        self.gener = None
        self.language = None

this is Code

#deserialize func~~~~~
print person.name #prints david
print person.age #prints 14
print person.gender #prints male
print person.language #prints "None"

Can I deserialize Json to class in Python(like C# Newtonsoft)

Thank you.


回答1:


You can use it with the json.loads() method. You would also need to ensure your JSON was a string and not just declared inline.

Here's an example program:

import json

js = '{"name":"david","age":14,"gender":"male"}'

class Person:
    def __init__(self, json_def):
        self.__dict__ = json.loads(json_def)

person = Person(js)

print person.name
print person.age
print person.gender

Just a note, though. When you attempt to use print person.language you will have an error, since it doesn't exist on the class.

EDIT

If there is a direct mapping desired, it would require explicit mapping of each possible object.

The following example will give each property a value if it exists in the JSON object and also solves the desire to use any missing properties:

import json

js = '{"name":"david","age":14,"gender":"male"}'

class Person(object):
    def __init__(self, json_def):
        s = json.loads(json_def)
        self.name = None if 'name' not in s else s['name']
        self.age = None if 'age' not in s else s['age']
        self.gender = None if 'gender' not in s else s['gender']
        self.language = None if 'language' not in s else s['language']

person = Person(js)

print person.name
print person.age
print person.gender
print person.language



回答2:


You can use the **kwargs like approach when we loads a json we will get a dict then we can just initialize our object with **json_def and get our object. for more complex json deserialization you will have to check the dict and take only the values that you need.

example:

class Person:
    def __init__(self, name=None, age=None, gender=None, language=None):
        self.name = name
        self.age = age
        self.gender = gender
        self.language = language


js = '{"name": "david", "age": 14, "gender": "male"}'
person = Person(**json.loads(js))
print(person.name)
js = '{"name": "david", "age": 14, "gender": "male", "language": "English"}'
person = Person(**json.loads(js))
print(person.language)


来源:https://stackoverflow.com/questions/42596710/can-i-deserialize-json-to-class-like-c-sharp-newtonsoft-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!