将Dart/Flutter中的Json解析为实体/模型

nx7onnlm  于 2023-01-05  发布在  Flutter
关注(0)|答案(3)|浏览(210)

"问候"

    • 将以下json转换为TodayWeather实体时遇到此问题:**

如何使用命名构造函数TodayHours?
这几天我一直在寻找解决这个问题的方法,但是我没有找到太多,请指导我。

    • 儿子:**
{
    "days": [
        {
            "datetime": "2023-01-05",
            "datetimeEpoch": 1672864200,
            "tempmax": 8.8,
            "tempmin": 2.3,
            "temp": 5.3,
            "windspeed": 8.6,
            "winddir": 223.9,
            "visibility": 19.7,
            "sunrise": "06:43:43",
            "sunset": "16:30:24",
            "conditions": "Snow, Rain, Overcast",
            "hours": [
                {
                    "datetime": "00:00:00",
                    "datetimeEpoch": 1672864200,
                    "temp": 4.4,
                    "humidity": 27.65,
                    "windspeed": 6.5,
                    "winddir": 249.2,
                    "visibility": 24.1,
                    "conditions": "Partially cloudy"
                },
                {
                    "datetime": "01:00:00",
                    "datetimeEpoch": 1672864200,
                    "temp": 4.4,
                    "humidity": 27.65,
                    "windspeed": 6.5,
                    "winddir": 249.2,
                    "visibility": 24.1,
                    "conditions": "Partially cloudy"
                }
            ]
        }
    ]
}
    • 我的今日天气实体是:**
class TodayWeather {
  final String datetime;
  final num dateEpoch;
  final String conditions;
  final num tempMax;
  final num tempMin;
  final num windDir;
  final num windSpeed;
  final String sunRise;
  final String sunSet;
  final num humidity;
  final num visibility;
  final List<TodayHourse> hours;

  TodayWeather.fromJson(Map<String, dynamic> json)
      : datetime = json['days'][0]['datetime'],
        dateEpoch = json['days'][0]['datetimeEpoch'],
        conditions = json['days'][0]['conditions'],
        tempMax = json['days'][0]['tempmax'],
        tempMin = json['days'][0]['tempmin'],
        windDir = json['days'][0]['winddir'],
        windSpeed = json['days'][0]['windspeed'],
        sunRise = json['days'][0]['sunrise'],
        sunSet = json['days'][0]['sunset'],
        humidity = json['days'][0]['humidity'],
        visibility = json['days'][0]['visibility'],
        hours = List<TodayHourse>.from(
            json['days'][0]['hours'].map((x) => x.toJson())).toList();
}
    • 并且我的TodayHours实体是:**
class TodayHourse {
  final String datetime;
  final num dateEpoch;
  final String conditions;
  final num temp;
  final num windDir;
  final num windSpeed;
  final num humidity;
  final num visibility;

  Map<String, dynamic> toJson() => {
        'datetime': datetime,
        'datetimeEpoch': dateEpoch,
        'conditions': conditions,
        'temp': temp,
        'winddir': windDir,
        'windspeed': windSpeed,
        'humidity': humidity,
        'visibility': visibility
      };

  TodayHourse.fromJson(Map<String, dynamic> json)
      : datetime = json['days'][0]['datetime'],
        dateEpoch = json['days'][0]['datetimeEpoch'],
        conditions = json['days'][0]['conditions'],
        temp = json['days'][0]['temp'],
        windDir = json['days'][0]['winddir'],
        windSpeed = json['days'][0]['windspeed'],
        humidity = json['days'][0]['humidity'],
        visibility = json['days'][0]['visibility'];
}
    • 此方法正在将Json解析为TodayWeather:**
@override
  Future<TodayWeather> getTodayWeather() async {
    final response = await httpClient.get(
        '36.31559%2C59.56796/today?unitGroup=metric&key=Key&contentType=json');
    validResponse(response);
    return TodayWeather.fromJson(response.data);
  }
carvr3hs

carvr3hs1#

首先将您的TodayHourse.fromJson更改为:

TodayHourse.fromJson(Map<String, dynamic> json)
      : datetime = json['datetime'],
        dateEpoch = json['datetimeEpoch'],
        conditions = json['conditions'],
        temp = json['temp'],
        windDir = json['winddir'],
        windSpeed = json['windspeed'],
        humidity = json['humidity'],
        visibility = json['visibility'];

你的hoursMap的列表,你不需要使用json['days'][0]。然后在你的TodayWeather.fromJson中,将hours更改为:

hours = (json['days'][0]['hours'] as List).map((x) => TodayHourse.fromJson(x)).toList();

你使用了错误的函数代替toJson,你需要调用TodayHourse.fromJson(x)

sigwle7e

sigwle7e2#

尝试使用此模型:

class TodayWeather {
  TodayWeather({required this.days});

  final List<Day> days;

  factory TodayWeather.fromJson(Map<String, dynamic> json) => TodayWeather(
        days: List<Day>.from(json["days"].map((x) => Day.fromJson(x))),
      );
}

class Day {
  Day({
    required this.datetime,
    required this.datetimeEpoch,
    required this.tempmax,
    required this.tempmin,
    required this.temp,
    required this.windspeed,
    required this.winddir,
    required this.visibility,
    required this.sunrise,
    required this.sunset,
    required this.conditions,
    required this.hours,
  });

  final DateTime datetime;
  final int datetimeEpoch;
  final double tempmax, tempmin, temp, windspeed, winddir, visibility;
  final String sunrise, sunset, conditions;
  final List<Hour> hours;

  factory Day.fromJson(Map<String, dynamic> json) => Day(
        datetime: DateTime.parse(json["datetime"]),
        datetimeEpoch: json["datetimeEpoch"],
        tempmax: json["tempmax"].toDouble(),
        tempmin: json["tempmin"].toDouble(),
        temp: json["temp"].toDouble(),
        windspeed: json["windspeed"].toDouble(),
        winddir: json["winddir"].toDouble(),
        visibility: json["visibility"].toDouble(),
        sunrise: json["sunrise"],
        sunset: json["sunset"],
        conditions: json["conditions"],
        hours: List<Hour>.from(json["hours"].map((x) => Hour.fromJson(x))),
      );
}

class Hour {
  Hour({
    required this.datetime,
    required this.datetimeEpoch,
    required this.temp,
    required this.humidity,
    required this.windspeed,
    required this.winddir,
    required this.visibility,
    required this.conditions,
  });

  final int datetimeEpoch;
  final double temp, humidity, windspeed, winddir, visibility;
  final String datetime, conditions;

  factory Hour.fromJson(Map<String, dynamic> json) => Hour(
        datetime: json["datetime"],
        datetimeEpoch: json["datetimeEpoch"],
        temp: json["temp"].toDouble(),
        humidity: json["humidity"].toDouble(),
        windspeed: json["windspeed"].toDouble(),
        winddir: json["winddir"].toDouble(),
        visibility: json["visibility"].toDouble(),
        conditions: json["conditions"],
      );
}
p3rjfoxz

p3rjfoxz3#

首先,为了更清楚地解析JSON数组,您可以在模型中创建helper方法,我将其命名为Model.fromJsonList

static List<WeatherDay> fromJsonList(dynamic jsonList) {
    if (jsonList == null || jsonList.isEmpty) return [];
    return (jsonList as List).map((e) => WeatherDay.fromJson(e)).toList();
  }

因此,通过这种方法,你可以解析数组响应非常容易和干净,例如:

Future<WeatherDay> fetchTodayWeather() async {
    final response = await httpClient.get(
        '36.31559%2C59.56796/today?unitGroup=metric&key=Key&contentType=json');
    final List<WeatherDay> weatherDays = WeatherDay.fromJsonList(response.data["days"]);
    return weatherDays.first;
  }

我们总共有:

class WeatherDay {
  WeatherDay( {
    @required this.datetime,
    @required this.hours,
  });

  final String datetime;
  final List<WeatherHour> hours;

  factory WeatherDay.fromJson(Map<String, dynamic> json) {
    return WeatherDay(
      datetime: json['datetime'] as String,
      hours: WeatherHour.fromJsonList(json['hours']),
    );
  }

  static List<WeatherDay> fromJsonList(dynamic jsonList) {
    if (jsonList == null || jsonList.isEmpty) return [];
    return (jsonList as List).map((e) => WeatherDay.fromJson(e)).toList();
  }
}

class WeatherHour {
  WeatherHour( {
    @required this.dateEpoch,
    @required this.conditions,
  });

  final num dateEpoch;
  final String conditions;

  factory WeatherHour.fromJson(Map<String, dynamic> json) {
    return WeatherHour(
      dateEpoch: json['datetimeEpoch'] as num,
      conditions: json['conditions'] as String,
    );
  }

  static List<WeatherHour> fromJsonList(dynamic jsonList) {
    if (jsonList == null || jsonList.isEmpty) return [];
    return (jsonList as List).map((e) => WeatherHour.fromJson(e)).toList();
  }
}
    • Note**:我没有分析所有的变量,你自己做吧。

相关问题