我可以反序列化Json到Python中的C#Newtonsoft之类的类吗 [英] Can I deserialize Json to class like C# Newtonsoft in Python

查看:95
本文介绍了我可以反序列化Json到Python中的C#Newtonsoft之类的类吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是json

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

这是python类

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

这是代码

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

我可以反序列化Json到Python(例如C#Newtonsoft)中的类

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

谢谢.

推荐答案

您可以将其与json.loads()方法一起使用.您还需要确保JSON是一个字符串,而不仅仅是声明为内联.

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.

这是一个示例程序:

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

不过,只是一个音符.尝试使用print person.language时,会出现错误,因为该错误在类中不存在.

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.

编辑

如果需要直接映射,则需要对每个可能的对象进行显式映射.

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

以下示例将为每个属性提供一个值(如果它存在于JSON对象中),并且还解决了使用任何缺少的属性的愿望:

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

这篇关于我可以反序列化Json到Python中的C#Newtonsoft之类的类吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆