skip to Main Content

I have recently started my journey in Flutter(Dart). I am trying to build an application which fetches some JSON information using an API call.

I have successfully written a code for the following JSON file

[
  {
    "on_api": "1",
    "tl_api": "10",
    "pl1_api": "Smoor Chocolates Lounge",
    "pl2_api": "Vasant Nagar",
    "dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
    "dl2_api": "Cunningham Road, Bengaluru - 560052",
    "fn_api": "Snehanshu",
    "ln_api": "Bhattacharya",
    "cn_api": "0123456789",
    "eid_api": "[email protected]"
  },
  {
    "on_api": "1",
    "tl_api": "10",
    "pl1_api": "Smoor Chocolates Lounge",
    "pl2_api": "Vasant Nagar",
    "dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
    "dl2_api": "Cunningham Road, Bengaluru - 560052",
    "fn_api": "Snehanshu",
    "ln_api": "Bhattacharya",
    "cn_api": "0123456789",
    "eid_api": "[email protected]"
  },
  {
    "on_api": "1",
    "tl_api": "10",
    "pl1_api": "Smoor Chocolates Lounge",
    "pl2_api": "Vasant Nagar",
    "dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
    "dl2_api": "Cunningham Road, Bengaluru - 560052",
    "fn_api": "Snehanshu",
    "ln_api": "Bhattacharya",
    "cn_api": "0123456789",
    "eid_api": "[email protected]"
  },
  {
    "on_api": "1",
    "tl_api": "10",
    "pl1_api": "Smoor Chocolates Lounge",
    "pl2_api": "Vasant Nagar",
    "dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
    "dl2_api": "Cunningham Road, Bengaluru - 560052",
    "fn_api": "Snehanshu",
    "ln_api": "Bhattacharya",
    "cn_api": "0123456789",
    "eid_api": "[email protected]"
  },
  {
    "on_api": "1",
    "tl_api": "10",
    "pl1_api": "Smoor Chocolates Lounge",
    "pl2_api": "Vasant Nagar",
    "dl1_api": "MySoftwareCompany Software Pvt. Ltd.",
    "dl2_api": "Cunningham Road, Bengaluru - 560052",
    "fn_api": "Snehanshu",
    "ln_api": "Bhattacharya",
    "cn_api": "0123456789",
    "eid_api": "[email protected]"
  }
]

Here is its element class

class Element {
  Element({
    this.onApi,
    this.tlApi,
    this.pl1Api,
    this.pl2Api,
    this.dl1Api,
    this.dl2Api,
    this.fnApi,
    this.lnApi,
    this.cnApi,
    this.eidApi,
  });

  String onApi;
  String tlApi;
  String pl1Api;
  String pl2Api;
  String dl1Api;
  String dl2Api;
  String fnApi;
  String lnApi;
  String cnApi;
  String eidApi;

  factory Element.fromJson(Map<String, dynamic> json) => Element(
    onApi: json["order_number"],
    tlApi: json["tl_api"],
    pl1Api: json["pl1_api"],
    pl2Api: json["pl2_api"],
    dl1Api: json["dl1_api"],
    dl2Api: json["dl2_api"],
    fnApi: json["fn_api"],
    lnApi: json["ln_api"],
    cnApi: json["cn_api"],
    eidApi: json["eid_api"],
  );
}

Here is its api calling code

import 'dart:convert';
import 'package:http/http.dart';
import 'package:smoorapplication/src/constants/constants.dart';
import 'package:smoorapplication/src/model/elements.dart';

Future<List<Element>> apiGetOrder() async{
  var response = await get(Uri.parse(MOCK_API_SMOOR_1));
  var jsonData = jsonDecode(response.body);
  List<Element> elements = <Element>[];
  for(var i in jsonData){
    Element element = Element.fromJson(i);
    elements.add(element);
  }
  print(elements.length);
}

I want the api call code and element class code for this kind of messy JSON file

{
  "orders": [
    {
      "id": 3927180738697,
      "admin_graphql_api_id": "gid://shopify/Order/00000",
      "app_id": 580111,
      "browser_ip": "122.172.179.207",
      "buyer_accepts_marketing": false,
      "cancel_reason": null,
      "cancelled_at": null,
      "cart_token": null,
      "checkout_id": 20726986440841,
      "checkout_token": "65651fdv561165",
      "client_details": {
        "accept_language": "en-US,en;q=0.9",
        "browser_height": 860,
        "browser_ip": "122.172.179.207",
        "browser_width": 1487,
        "session_hash": null,
      },
      "closed_at": null,
      "confirmed": true,
      "contact_email": null,
      "created_at": "2021-12-16T11:03:59+05:30",
      "currency": "INR",
      "current_subtotal_price": "500.00",
      "current_subtotal_price_set": {
        "shop_money": {
          "amount": "500.00",
          "currency_code": "INR"
        },
        "presentment_money": {
          "amount": "500.00",
          "currency_code": "INR"
        }
      },
      "current_total_discounts": "0.00",
      "current_total_discounts_set": {
        "shop_money": {
          "amount": "0.00",
          "currency_code": "INR"
        },
        "presentment_money": {
          "amount": "0.00",
          "currency_code": "INR"
        }
      },
      "current_total_duties_set": null,
      "current_total_price": "600.00",
      "current_total_price_set": {
        "shop_money": {
          "amount": "600.00",
          "currency_code": "INR"
        },
        "presentment_money": {
          "amount": "600.00",
          "currency_code": "INR"
        }
      },
      "current_total_tax": "91.52",
      "current_total_tax_set": {
        "shop_money": {
          "amount": "91.52",
          "currency_code": "INR"
        },
        "presentment_money": {
          "amount": "91.52",
          "currency_code": "INR"
        }
      }
    }
  ]
}

2

Answers


  1. I guess you can come up with an API call method (similar to which you already have done). The JSON which you are providing has different sub levels. So, you could use different classes for it. For simplification there are tools out there which converts JSON to Dart. You could look for them. Once such tool is this.

    API calling would most probably be just adding it in a root element. I guess it should take care of the rest. (because the inter dependency classes are also included when converting JSON to dart)

    I tried to convert your JSON (which had an extra comma in line:19) and below is the result I got.

    class Element {
      List<Orders> orders;
    
      Element({this.orders});
    
      Element.fromJson(Map<String, dynamic> json) {
        if (json['orders'] != null) {
          orders = new List<Orders>();
          json['orders'].forEach((v) {
            orders.add(new Orders.fromJson(v));
          });
        }
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        if (this.orders != null) {
          data['orders'] = this.orders.map((v) => v.toJson()).toList();
        }
        return data;
      }
    }
    
    class Orders {
      int id;
      String adminGraphqlApiId;
      int appId;
      String browserIp;
      bool buyerAcceptsMarketing;
      Null cancelReason;
      Null cancelledAt;
      Null cartToken;
      int checkoutId;
      String checkoutToken;
      ClientDetails clientDetails;
      Null closedAt;
      bool confirmed;
      Null contactEmail;
      String createdAt;
      String currency;
      String currentSubtotalPrice;
      CurrentSubtotalPriceSet currentSubtotalPriceSet;
      String currentTotalDiscounts;
      CurrentSubtotalPriceSet currentTotalDiscountsSet;
      Null currentTotalDutiesSet;
      String currentTotalPrice;
      CurrentSubtotalPriceSet currentTotalPriceSet;
      String currentTotalTax;
      CurrentSubtotalPriceSet currentTotalTaxSet;
    
      Orders(
          {this.id,
          this.adminGraphqlApiId,
          this.appId,
          this.browserIp,
          this.buyerAcceptsMarketing,
          this.cancelReason,
          this.cancelledAt,
          this.cartToken,
          this.checkoutId,
          this.checkoutToken,
          this.clientDetails,
          this.closedAt,
          this.confirmed,
          this.contactEmail,
          this.createdAt,
          this.currency,
          this.currentSubtotalPrice,
          this.currentSubtotalPriceSet,
          this.currentTotalDiscounts,
          this.currentTotalDiscountsSet,
          this.currentTotalDutiesSet,
          this.currentTotalPrice,
          this.currentTotalPriceSet,
          this.currentTotalTax,
          this.currentTotalTaxSet});
    
      Orders.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        adminGraphqlApiId = json['admin_graphql_api_id'];
        appId = json['app_id'];
        browserIp = json['browser_ip'];
        buyerAcceptsMarketing = json['buyer_accepts_marketing'];
        cancelReason = json['cancel_reason'];
        cancelledAt = json['cancelled_at'];
        cartToken = json['cart_token'];
        checkoutId = json['checkout_id'];
        checkoutToken = json['checkout_token'];
        clientDetails = json['client_details'] != null
            ? new ClientDetails.fromJson(json['client_details'])
            : null;
        closedAt = json['closed_at'];
        confirmed = json['confirmed'];
        contactEmail = json['contact_email'];
        createdAt = json['created_at'];
        currency = json['currency'];
        currentSubtotalPrice = json['current_subtotal_price'];
        currentSubtotalPriceSet = json['current_subtotal_price_set'] != null
            ? new CurrentSubtotalPriceSet.fromJson(
                json['current_subtotal_price_set'])
            : null;
        currentTotalDiscounts = json['current_total_discounts'];
        currentTotalDiscountsSet = json['current_total_discounts_set'] != null
            ? new CurrentSubtotalPriceSet.fromJson(
                json['current_total_discounts_set'])
            : null;
        currentTotalDutiesSet = json['current_total_duties_set'];
        currentTotalPrice = json['current_total_price'];
        currentTotalPriceSet = json['current_total_price_set'] != null
            ? new CurrentSubtotalPriceSet.fromJson(json['current_total_price_set'])
            : null;
        currentTotalTax = json['current_total_tax'];
        currentTotalTaxSet = json['current_total_tax_set'] != null
            ? new CurrentSubtotalPriceSet.fromJson(json['current_total_tax_set'])
            : null;
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['admin_graphql_api_id'] = this.adminGraphqlApiId;
        data['app_id'] = this.appId;
        data['browser_ip'] = this.browserIp;
        data['buyer_accepts_marketing'] = this.buyerAcceptsMarketing;
        data['cancel_reason'] = this.cancelReason;
        data['cancelled_at'] = this.cancelledAt;
        data['cart_token'] = this.cartToken;
        data['checkout_id'] = this.checkoutId;
        data['checkout_token'] = this.checkoutToken;
        if (this.clientDetails != null) {
          data['client_details'] = this.clientDetails.toJson();
        }
        data['closed_at'] = this.closedAt;
        data['confirmed'] = this.confirmed;
        data['contact_email'] = this.contactEmail;
        data['created_at'] = this.createdAt;
        data['currency'] = this.currency;
        data['current_subtotal_price'] = this.currentSubtotalPrice;
        if (this.currentSubtotalPriceSet != null) {
          data['current_subtotal_price_set'] =
              this.currentSubtotalPriceSet.toJson();
        }
        data['current_total_discounts'] = this.currentTotalDiscounts;
        if (this.currentTotalDiscountsSet != null) {
          data['current_total_discounts_set'] =
              this.currentTotalDiscountsSet.toJson();
        }
        data['current_total_duties_set'] = this.currentTotalDutiesSet;
        data['current_total_price'] = this.currentTotalPrice;
        if (this.currentTotalPriceSet != null) {
          data['current_total_price_set'] = this.currentTotalPriceSet.toJson();
        }
        data['current_total_tax'] = this.currentTotalTax;
        if (this.currentTotalTaxSet != null) {
          data['current_total_tax_set'] = this.currentTotalTaxSet.toJson();
        }
        return data;
      }
    }
    
    class ClientDetails {
      String acceptLanguage;
      int browserHeight;
      String browserIp;
      int browserWidth;
      Null sessionHash;
    
      ClientDetails(
          {this.acceptLanguage,
          this.browserHeight,
          this.browserIp,
          this.browserWidth,
          this.sessionHash});
    
      ClientDetails.fromJson(Map<String, dynamic> json) {
        acceptLanguage = json['accept_language'];
        browserHeight = json['browser_height'];
        browserIp = json['browser_ip'];
        browserWidth = json['browser_width'];
        sessionHash = json['session_hash'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['accept_language'] = this.acceptLanguage;
        data['browser_height'] = this.browserHeight;
        data['browser_ip'] = this.browserIp;
        data['browser_width'] = this.browserWidth;
        data['session_hash'] = this.sessionHash;
        return data;
      }
    }
    
    class CurrentSubtotalPriceSet {
      ShopMoney shopMoney;
      ShopMoney presentmentMoney;
    
      CurrentSubtotalPriceSet({this.shopMoney, this.presentmentMoney});
    
      CurrentSubtotalPriceSet.fromJson(Map<String, dynamic> json) {
        shopMoney = json['shop_money'] != null
            ? new ShopMoney.fromJson(json['shop_money'])
            : null;
        presentmentMoney = json['presentment_money'] != null
            ? new ShopMoney.fromJson(json['presentment_money'])
            : null;
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        if (this.shopMoney != null) {
          data['shop_money'] = this.shopMoney.toJson();
        }
        if (this.presentmentMoney != null) {
          data['presentment_money'] = this.presentmentMoney.toJson();
        }
        return data;
      }
    }
    
    class ShopMoney {
      String amount;
      String currencyCode;
    
      ShopMoney({this.amount, this.currencyCode});
    
      ShopMoney.fromJson(Map<String, dynamic> json) {
        amount = json['amount'];
        currencyCode = json['currency_code'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['amount'] = this.amount;
        data['currency_code'] = this.currencyCode;
        return data;
      }
    }
    
    Login or Signup to reply.
  2. To call API your method is sufficient you just need to return value from your function according to the return type of your function. In your function you have a return type of List<Element> so you need to perform some changes in your code

    Future<List<Element>> apiGetOrder() async{
      var response = await get(Uri.parse(MOCK_API_SMOOR_1));
      var jsonData = jsonDecode(response.body)["orders"];
      List<Element> elements = <Element>[];
      for(var i in jsonData){
        Element element = Element.fromJson(i);
        elements.add(element);
      }
      print(elements.length);
    
      return elements; // returning value
    }
    

    and for creating a class according to the response you can use a handy tool which Quicktype I’m also sharing link for the same

    https://app.quicktype.io/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search