json Deserialization of Python Objects

news2024/9/23 12:24:08

openweathermap.json


{
	"coord": {
		"lon": 114.0683, "lat":22.5455
	}

	,
	"weather":[ {
		"id": 803, "main":"Clouds", "description":"多云", "icon":"04d"
	}

	],
	"base":"stations",
	"main": {
		"temp": 299.1, "feels_like":299.1, "temp_min":296.39, "temp_max":300.29, "pressure":1018, "humidity":79, "sea_level":1018, "grnd_level":1017
	}

	,
	"visibility":10000,
	"wind": {
		"speed": 2.73, "deg":137, "gust":3.32
	}

	,
	"clouds": {
		"all": 82
	}

	,
	"dt":1702530001,
	"sys": {
		"type": 2, "id":2031340, "country":"CN", "sunrise":1702508106, "sunset":1702546869
	}

	,
	"timezone":28800,
	"id":1795565,
	"name":"Shenzhen",
	"cod":200
}

# encoding: utf-8
# 版权所有 2023 涂聚文有限公司
# 许可信息查看:
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# Datetime  : 2023/12/14 22:14
# User      : geovindu
# Product   : PyCharm
# Project   : pyBaiduAi
# File      : Clouds.py
# explain   : 学习

import json
import pickle
from typing import List
from typing import Any
from dataclasses import dataclass



@dataclass
class Clouds:
    all: int

    @staticmethod
    def from_dict(obj: Any) -> 'Clouds':
        _all = int(obj.get("all"))
        return Clouds(_all)


@dataclass
class Coord:
    lon: float
    """
    经度
    """
    lat: float
    """
    纬度
    """
    @staticmethod
    def from_dict(obj: Any) -> 'Coord':
        _lon = float(obj.get("lon"))
        _lat = float(obj.get("lat"))
        return Coord(_lon, _lat)


@dataclass
class Main:
    """

    """
    temp: float
    """
    温度 
    """

    feels_like: float
    temp_min: float
    """
    最低温
    """
    temp_max: float
    """
    最高温
    """
    pressure: int
    humidity: int
    """
    湿魔
    """
    sea_level: int
    grnd_level: int

    @staticmethod
    def from_dict(obj: Any) -> 'Main':
        _temp = float(obj.get("temp"))
        _feels_like = float(obj.get("feels_like"))
        _temp_min = float(obj.get("temp_min"))
        _temp_max = float(obj.get("temp_max"))
        _pressure = int(obj.get("pressure"))
        _humidity = int(obj.get("humidity"))
        _sea_level = int(obj.get("sea_level"))
        _grnd_level = int(obj.get("grnd_level"))
        return Main(_temp, _feels_like, _temp_min, _temp_max, _pressure, _humidity, _sea_level, _grnd_level)


@dataclass
class Sys:
    """
    系统信息
    """
    type: int
    id: int
    country: str
    """
    所属国家
    """
    sunrise: int
    """
    日出时间戳
    """
    sunset: int
    """
    日落时间戳
    """

    @staticmethod
    def from_dict(obj: Any) -> 'Sys':
        _type = int(obj.get("type"))
        _id = int(obj.get("id"))
        _country = str(obj.get("country"))
        _sunrise = int(obj.get("sunrise"))
        _sunset = int(obj.get("sunset"))
        return Sys(_type, _id, _country, _sunrise, _sunset)


@dataclass
class Weather:
    """
    天气情况
    """
    id: int
    main: str
    description: str
    """
    天气
    """
    icon: str
    """
    图标ID
    """

    @staticmethod
    def from_dict(obj: Any) -> 'Weather':
        _id = int(obj.get("id"))
        _main = str(obj.get("main"))
        _description = str(obj.get("description"))
        _icon = str(obj.get("icon"))
        return Weather(_id, _main, _description, _icon)


@dataclass
class Wind:
    """
    风况
    """
    speed: float
    """
    风速
    """
    deg: int
    gust: float

    @staticmethod
    def from_dict(obj: Any) -> 'Wind':
        _speed = float(obj.get("speed"))
        _deg = int(obj.get("deg"))
        _gust = float(obj.get("gust"))
        return Wind(_speed, _deg, _gust)

@dataclass
class OpenWeather:
    """"
    天气类
    """
    coord: Coord
    weather: List[Weather]
    base: str
    main: Main
    visibility: int
    wind: Wind
    clouds: Clouds
    dt: int
    sys: Sys
    timezone: int
    id: int
    name: str
    cod: int

    @staticmethod
    def from_dict(obj: Any) -> 'OpenWeather':
        _coord = Coord.from_dict(obj.get("coord"))
        _weather = [Weather.from_dict(y) for y in obj.get("weather")]
        _base = str(obj.get("base"))
        _main = Main.from_dict(obj.get("main"))
        _visibility = int(obj.get("visibility"))
        _wind = Wind.from_dict(obj.get("wind"))
        _clouds = Clouds.from_dict(obj.get("clouds"))
        _dt = int(obj.get("dt"))
        _sys = Sys.from_dict(obj.get("sys"))
        _timezone = int(obj.get("timezone"))
        _id = int(obj.get("id"))
        _name = str(obj.get("name"))
        _cod = int(obj.get("cod"))
        return OpenWeather(_coord, _weather, _base, _main, _visibility, _wind, _clouds, _dt, _sys, _timezone, _id, _name, _cod)

调用:


import Model.Clouds



def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name} world,geovindu,涂聚文')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm,geovindu')

    #deserialization process:
    with open('openweathermap.json',encoding='utf-8') as json_file:
        data = json.load(json_file)
        print("data from file:")
        print(type(data))
        root=Model.Clouds.OpenWeather.from_dict(data)
        print(root)
        print("湿度",root.main.humidity)
        print("天气:", root.weather[0].description)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1311326.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MacOS多屏状态栏位置不固定,程序坞不小心跑到副屏

目录 方式一:通过系统设置方式二:鼠标切换 MacOS多屏状态栏位置不固定,程序坞不小心跑到副屏 方式一:通过系统设置 先切换到左边 再切换到底部 就能回到主屏了 方式二:鼠标切换 我的两个屏幕放置位置如下 鼠标在…

R语言【rgbif】——什么是多值传参?如何在rgbif中一次性传递多个值?多值传参时的要求有哪些?

rgbif版本:3.7.8.1 什么是多值传参? 您是否在使用rgbif时设想过,给某个参数一次性传递许多个值,它将根据这些值独立地进行请求,各自返回独立的结果。 rgbif支持这种工作模式,但是具体的细节需要进一步地…

蓝牙物联网智慧物业解决方案

蓝牙物联网智慧物业解决方案是一种利用蓝牙技术来提高物业管理和服务效率的解决方案。它通过将蓝牙技术与其他智能设备、应用程序和云服务相结合,为物业管理和服务提供更便捷、高效和智能化的支持。 蓝牙物联网智慧物业解决方案包括: 1、设备管理&#…

Crypto基础之密码学

FLAG:20岁的年纪不该困在爱与不爱里,对吗 专研方向: 密码学,Crypto 每日emo:今年你失去了什么? Crypto基础之密码学 前言一、编码Base编码base64:Base32 和 Base16:uuencode:xxencod…

计算机网络——网络层——OSPF协议的介绍

什么是 OSPF ? OSPF 是一个基于链路状态的自治系统内部路由协议,在 TCP/IP 的网络层中进行路由选择,常用于构建大型企业网络或者服务上的骨干网络。在互联网核心路由器之间也可以使用。 OSPF 概述 OSPF 使用的是 Dijkstra(最短…

智能优化算法应用:基于黏菌算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用:基于黏菌算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用:基于黏菌算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.黏菌算法4.实验参数设定5.算法结果6.参考文献7.MA…

记录 | mac打开终端时报错:login: /opt/homebrew/bin/zsh: No such file or directory [进程已完成]

mac打开终端时报错:login: /opt/homebrew/bin/zsh: No such file or directory [进程已完成],导致终端没有办法使用的情况 说明 zsh 没有安装或者是安装路径不对 可以看看 /bin 下有没有 zsh,若没有,肯定是有 bash 那就把终端默…

QT- QT-lximagerEidtor图片编辑器

QT- QT-lximagerEidtor图片编辑器 一、演示效果二、关键程序三、下载链接 功能如下: 1、缩放、旋转、翻转和调整图像大小 2、幻灯片 3、缩略图栏(左、上或下);不同的缩略图大小 4、Exif数据栏 5、内联图像重命名 6、自定义快捷方式…

JS加密/解密之JSX解密解析(photoshop插件)

简介 Adobe Photoshop 插件通常使用 JSX(JavaScript XML)脚本语言。这是一种基于JavaScript的扩展,专门设计用于处理Adobe Creative Suite(包括Photoshop)的任务。JSX脚本允许开发者编写自定义脚本以扩展和增强Photos…

【Eureka】自定义元数据消失原因?

【Eureka】自定义元数据运行很长一段时间后,自定义元数据(scheduler.server.enabled)偶尔会消失,但服务元数据信息还在 eureka是单节点的,这个应用服务也是单节点的 代码实现方式如下 我看过eureka服务的日志信息&…

在做题中学习(33):只出现一次的数字 II

137. 只出现一次的数字 II - 力扣(LeetCode) 思路: 1.首先想到出现三次的数,它们仨的任意一位都是相同的(1/0) 2.可以发现出现三次的数的某一位和a某一位在所有情况下%3最后的结果都和a的那一位相同&…

06.迪米特法则(Demeter Principle)

明 嘉靖四十年 江南织造总局 小黄门唯唯诺诺的听完了镇守太监杨金水的训斥,赶忙回答:“知道了,干爹!” “知道什么?!!” 杨金水打断了他的话,眼神突然变得凌厉起来: “有…

企业计算机服务器中了halo勒索病毒如何解密,halo勒索病毒恢复流程

网络技术的不断发展与应用,为企业的生产运营提供了极大便利,越来越多的企业使用数据库存储企业的重要数据,方便工作与生产,但网络是一把双刃剑,网络安全威胁一直存在,并且网络威胁的手段也在不断升级。在本…

我的隐私计算学习——匿踪查询

笔记内容来自多本书籍、学术资料、白皮书及ChatGPT等工具,经由自己阅读后整理而成。 (一)PIR的介绍 ​ 匿踪查询,即隐私信息检索(Private InformationRetrieval,PIR),是安全多方计算…

C# OpenVINO 直接读取百度模型实现印章检测

目录 效果 模型信息 项目 代码 下载 其他 C# OpenVINO 直接读取百度模型实现印章检测 效果 模型信息 Inputs ------------------------- name:scale_factor tensor:F32[?, 2] name:image tensor:F32[?, 3, 608, 608] …

Windows更改远程桌面端口并添加防火墙入站规则

1.运行 快捷键winR组合键,win就是键盘上的windows系统图标键。 2.打开注册表 Regedit,在对话框中输入regedit命令,然后回车 3.打开注册表,输入命令后,会打开系统的注册表,左边是目录栏,右边是…

基于STM32的智能小区环境监测

一、概述 本系统应用STM32F407VET6单片机为控制处理器,加上外设备组成单片机最小系统。配以输入输出部分,通过采集温湿度、甲醛、PM2.5等数据在LCD液晶上显示,内加单独时钟晶振电路,保护断电后时间参数不变,外接5v电源…

QGIS 加载在线XYZ地图图层

QGIS 加载在线XYZ地图图层 定义并添加必应XYZ图层 Go to Layer > Add Layer > Add XYZ Layer…Click NewName as BingMaps(as you wish)URL as http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g1click OkSelect XYZ Connections as Bing Maps(Which you creat…

C++之获取变量信息名称、类型typeid

摘要 对于C工程量级比较庞大的代码,代码中的变量、类、函数、结构体的识别都是一件让人头疼的事情,一方面代码越写越多,内容越来越丰富,但是没有办法对已有的代码框架进行高度的整合提炼;另一方面对新人逐渐不友好&am…

python 协程

python 协程 协程为什么需要协程?协程与子线程的区别协程的工作原理协程的优缺点协程优点协程缺点 协程的实现yield 关键字greenlet 模块gevent 模块Pool 限制并发 协程 协程又称微线程,英文名coroutine。协程是用户态的一种轻量级线程,是由…