Home > Back-end >  How do i parse and access elements of json strings in flutter
How do i parse and access elements of json strings in flutter

Time:12-31

I am currently trying to parse this json string:

  {"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}

I created this class:

 class ParseJSON {
  ParseJSON({
    this.imsak,
    this.sunrise,
    this.fajr,
    this.dhuhr,
    this.asr,
    this.sunset,
    this.maghrib,
    this.isha,
    this.midnight,
  });

  String imsak;
  String sunrise;
  String fajr;
  String dhuhr;
  String asr;
  String sunset;
  String maghrib;
  String isha;
  String midnight;

  factory ParseJSON.fromJson(Map<String, dynamic> json) => ParseJSON(
    imsak: json["Imsak"],
    sunrise: json["Sunrise"],
    fajr: json["Fajr"],
    dhuhr: json["Dhuhr"],
    asr: json["Asr"],
    sunset: json["Sunset"],
    maghrib: json["Maghrib"],
    isha: json["Isha"],
    midnight: json["Midnight"],
  );

  Map<String, dynamic> toJson() => {
    "Imsak": imsak,
    "Sunrise": sunrise,
    "Fajr": fajr,
    "Dhuhr": dhuhr,
    "Asr": asr,
    "Sunset": sunset,
    "Maghrib": maghrib,
    "Isha": isha,
    "Midnight": midnight,
  };
}

I tried to access the contents of the json thus:

Future<List<ParseJSON>> fetchJSON() async {         

     String jsonResponse = """
  {"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
  """;  

     ParseJSON welcomeFromJson(String str) => ParseJSON.fromJson(json.decode(str));

     final welcome = welcomeFromJson(jsonResponse);

     print("Printing contents from json string");
     //print(jsonResponse);
     print(welcome.maghrib);
     print(welcome.fajr);
    
  }

The problem is that both print(welcome.maghrib) and print(welcome.fajr) return null. Please what am i doing incorrectly? Any help would be appreciated. Thanks

CodePudding user response:

Your model class is for only getting "times" object, so you need below change for parsing Json or you need to change your model class for parsing every field from Response.

Future<List<ParseJSON>?> fetchJSON() async {
    String jsonResponse = """
  {"code":200,"status":"OK","results":{"datetime":[{"times":{"Imsak":"05:21","Sunrise":"06:43","Fajr":"05:31","Dhuhr":"12:32","Asr":"15:51","Sunset":"18:22","Maghrib":"18:32","Isha":"19:33","Midnight":"23:57"},"date":{"timestamp":1640736000,"gregorian":"2021-12-29","hijri":"1443-05-25"}}],"location":{"latitude":10.516667366027832,"longitude":7.433332920074462,"elevation":611.0,"city":"Kaduna","country":"Nigeria","country_code":"NG","timezone":"Africa/Lagos","local_offset":1.0},"settings":{"timeformat":"HH:mm","school":"Ithna Ashari","juristic":"Shafii","highlat":"None","fajr_angle":18.0,"isha_angle":18.0}}}
  """;
    var response = json.decode(jsonResponse);
    ParseJSON welcome = ParseJSON.fromJson(response['results']['datetime'][0]['times']);

    print("Printing contents from json string");
    //print(jsonResponse);
    print(welcome.maghrib);
    print(welcome.fajr);
  }

CodePudding user response:

You can try out using this code :

import 'dart:convert';

ParseJson parseJsonFromJson(String str) => ParseJson.fromJson(json.decode(str));

String parseJsonToJson(ParseJson data) => json.encode(data.toJson());

class ParseJson {
    ParseJson({
        this.code,
        this.status,
        this.results,
    });

    int code;
    String status;
    Results results;

    factory ParseJson.fromJson(Map<String, dynamic> json) => ParseJson(
        code: json["code"],
        status: json["status"],
        results: Results.fromJson(json["results"]),
    );

    Map<String, dynamic> toJson() => {
        "code": code,
        "status": status,
        "results": results.toJson(),
    };
}

class Results {
    Results({
        this.datetime,
        this.location,
        this.settings,
    });

    List<Datetime> datetime;
    Location location;
    Settings settings;

    factory Results.fromJson(Map<String, dynamic> json) => Results(
        datetime: List<Datetime>.from(json["datetime"].map((x) => Datetime.fromJson(x))),
        location: Location.fromJson(json["location"]),
        settings: Settings.fromJson(json["settings"]),
    );

    Map<String, dynamic> toJson() => {
        "datetime": List<dynamic>.from(datetime.map((x) => x.toJson())),
        "location": location.toJson(),
        "settings": settings.toJson(),
    };
}

class Datetime {
    Datetime({
        this.times,
        this.date,
    });

    Times times;
    Date date;

    factory Datetime.fromJson(Map<String, dynamic> json) => Datetime(
        times: Times.fromJson(json["times"]),
        date: Date.fromJson(json["date"]),
    );

    Map<String, dynamic> toJson() => {
        "times": times.toJson(),
        "date": date.toJson(),
    };
}

class Date {
    Date({
        this.timestamp,
        this.gregorian,
        this.hijri,
    });

    int timestamp;
    DateTime gregorian;
    DateTime hijri;

    factory Date.fromJson(Map<String, dynamic> json) => Date(
        timestamp: json["timestamp"],
        gregorian: DateTime.parse(json["gregorian"]),
        hijri: DateTime.parse(json["hijri"]),
    );

    Map<String, dynamic> toJson() => {
        "timestamp": timestamp,
        "gregorian": "${gregorian.year.toString().padLeft(4, '0')}-${gregorian.month.toString().padLeft(2, '0')}-${gregorian.day.toString().padLeft(2, '0')}",
        "hijri": "${hijri.year.toString().padLeft(4, '0')}-${hijri.month.toString().padLeft(2, '0')}-${hijri.day.toString().padLeft(2, '0')}",
    };
}

class Times {
    Times({
        this.imsak,
        this.sunrise,
        this.fajr,
        this.dhuhr,
        this.asr,
        this.sunset,
        this.maghrib,
        this.isha,
        this.midnight,
    });

    String imsak;
    String sunrise;
    String fajr;
    String dhuhr;
    String asr;
    String sunset;
    String maghrib;
    String isha;
    String midnight;

    factory Times.fromJson(Map<String, dynamic> json) => Times(
        imsak: json["Imsak"],
        sunrise: json["Sunrise"],
        fajr: json["Fajr"],
        dhuhr: json["Dhuhr"],
        asr: json["Asr"],
        sunset: json["Sunset"],
        maghrib: json["Maghrib"],
        isha: json["Isha"],
        midnight: json["Midnight"],
    );

    Map<String, dynamic> toJson() => {
        "Imsak": imsak,
        "Sunrise": sunrise,
        "Fajr": fajr,
        "Dhuhr": dhuhr,
        "Asr": asr,
        "Sunset": sunset,
        "Maghrib": maghrib,
        "Isha": isha,
        "Midnight": midnight,
    };
}

class Location {
    Location({
        this.latitude,
        this.longitude,
        this.elevation,
        this.city,
        this.country,
        this.countryCode,
        this.timezone,
        this.localOffset,
    });

    double latitude;
    double longitude;
    int elevation;
    String city;
    String country;
    String countryCode;
    String timezone;
    int localOffset;

    factory Location.fromJson(Map<String, dynamic> json) => Location(
        latitude: json["latitude"].toDouble(),
        longitude: json["longitude"].toDouble(),
        elevation: json["elevation"],
        city: json["city"],
        country: json["country"],
        countryCode: json["country_code"],
        timezone: json["timezone"],
        localOffset: json["local_offset"],
    );

    Map<String, dynamic> toJson() => {
        "latitude": latitude,
        "longitude": longitude,
        "elevation": elevation,
        "city": city,
        "country": country,
        "country_code": countryCode,
        "timezone": timezone,
        "local_offset": localOffset,
    };
}

class Settings {
    Settings({
        this.timeformat,
        this.school,
        this.juristic,
        this.highlat,
        this.fajrAngle,
        this.ishaAngle,
    });

    String timeformat;
    String school;
    String juristic;
    String highlat;
    int fajrAngle;
    int ishaAngle;

    factory Settings.fromJson(Map<String, dynamic> json) => Settings(
        timeformat: json["timeformat"],
        school: json["school"],
        juristic: json["juristic"],
        highlat: json["highlat"],
        fajrAngle: json["fajr_angle"],
        ishaAngle: json["isha_angle"],
    );

    Map<String, dynamic> toJson() => {
        "timeformat": timeformat,
        "school": school,
        "juristic": juristic,
        "highlat": highlat,
        "fajr_angle": fajrAngle,
        "isha_angle": ishaAngle,
    };
}

just call this line when parse json:

final parseJson = parseJsonFromJson(jsonString);
  • Related