Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 491
hero Avatar asked Jan 05 '23 10:01

hero


1 Answers

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
like image 182
Derek Avatar answered Jan 07 '23 12:01

Derek