Home > OS >  Parsing JSON data from a model PODO
Parsing JSON data from a model PODO

Time:07-28

i have a PODO created for my model. See below:

class Data {

  String? parentWo;
  String? parentWoDesc;
  String? parentWoStatus;
  String? parentWoStatusDate;
  String? parentWoWorkType;
  String? parentWoClass;
  String? parentWoCrew;
  String? parentWoLead;
  String? parentWoLocation;
  String? parentWoDepartmentDescription;
  String? parentWoSectionDescription;
  List<Child>? children;

  Data({
    this.parentWo,
    this.parentWoDesc,
    this.parentWoStatus,
    this.parentWoStatusDate,
    this.parentWoWorkType,
    this.parentWoClass,
    this.parentWoCrew,
    this.parentWoLead,
    this.parentWoLocation,
    this.parentWoDepartmentDescription,
    this.parentWoSectionDescription,
    this.children,
  });

  factory Data.fromJson(Map<String, dynamic> json) {
    var list = json['children'] as List;
    print(list.runtimeType);
    List<Child> childrenlist = list.map((i) => Child.fromJson(i)).toList();

    return Data(
      parentWo: json["parentWo"] ?? 'VADER',
      parentWoDesc: json["parentWoDesc"],
      parentWoStatus: json["parentWoStatus"],
      parentWoStatusDate: json["parentWoStatusDate"],
      parentWoWorkType: json["parentWoWorkType"],
      parentWoClass: json["parentWoClass"],
      parentWoCrew: json["parentWoCrew"],
      parentWoLead: json["parentWoLead"],
      parentWoLocation: json["parentWoLocation"],
      parentWoDepartmentDescription: json["parentWoDepartmentDescription"],
      parentWoSectionDescription: json["parentWoSectionDescription"],
      children:
          childrenlist,
    );
  }
  

  Map<String, dynamic> toJson() => {
        "parentWo": parentWo,
        "parentWoDesc": parentWoDesc,
        "parentWoStatus": parentWoStatus,
        "parentWoStatusDate": parentWoStatusDate,
        "parentWoWorkType": parentWoWorkType,
        "parentWoClass": parentWoClass,
        "parentWoCrew": parentWoCrew,
        "parentWoLead": parentWoLead,
        "parentWoLocation": parentWoLocation,
        "parentWoDepartmentDescription": parentWoDepartmentDescription,
        "parentWoSectionDescription": parentWoSectionDescription,
        "children": List<dynamic>.from(children!.map((x) => x.toJson())),
      };
}

class Child {

  String? woNum;
  String? woDesc;
  String? woStatus;
  DateTime? woStatusDate;
  String? woCrew;
  String? woLead;
  String? woLocation;
  List<Materials>? materials;

  Child({
    this.woNum,
    this.woDesc,
    this.woStatus,
    this.woStatusDate,
    this.woCrew,
    this.woLead,
    this.woLocation,
    this.materials,
  });

  factory Child.fromJson(Map<String, dynamic> json) {
    var list = json['materials'] as List;
    print(list.runtimeType);
    List<Materials> materialslist = list.map((i) => Materials.fromJson(i)).toList();

    return Child(
        woNum: json["woNum"],
        woDesc: json["woDesc"],
        woStatus: json["woStatus"],
        woStatusDate: DateTime.parse(json["woStatusDate"]),
        woCrew: json["woCrew"],
        woLead: json["woLead"],
        woLocation: json["woLocation"],
        materials: materialslist,
      );
  } 

  Map<String, dynamic> toJson() => {
        "woNum": woNum,
        "woDesc": woDesc,
        "woStatus": woStatus,
        "woStatusDate": woStatusDate!.toIso8601String(),
        "woCrew": woCrew,
        "woLead": woLead,
        "woLocation": woLocation,
        "materials": List<dynamic>.from(materials!.map((x) => x.toJson())),
      };
  get length => null;
}

class Materials {

  String? itemNum;
  String? itemDescription;
  int? itemQuantityPlan;
  int? itemQuantityIssued;
  int? itemWoBalance;
  int? itemInventoryBalance;
  String? itemCommodity;
  String? itemIssueUnit;
  bool? itemStructure;
  bool? itemDtPole;
  
  Materials({
    this.itemNum,
    this.itemDescription,
    this.itemQuantityPlan,
    this.itemQuantityIssued,
    this.itemWoBalance,
    this.itemInventoryBalance,
    this.itemCommodity,
    this.itemIssueUnit,
    this.itemStructure,
    this.itemDtPole,
  });

  factory Materials.fromJson(Map<String, dynamic> json) => Materials(
        itemNum: json["itemNum"],
        itemDescription: json["itemDescription"],
        itemQuantityPlan: json["itemQuantityPlan"],
        itemQuantityIssued: json["itemQuantityIssued"],
        itemWoBalance: json["itemWoBalance"],
        itemInventoryBalance: json["itemInventoryBalance"],
        itemCommodity: json["itemCommodity"],
        itemIssueUnit: json["itemIssueUnit"],
        itemStructure: json["itemStructure"],
        itemDtPole: json["itemDtPole"],
      );

  Map<String, dynamic> toJson() => {
        "itemNum": itemNum,
        "itemDescription": itemDescription,
        "itemQuantityPlan": itemQuantityPlan,
        "itemQuantityIssued": itemQuantityIssued,
        "itemWoBalance": itemWoBalance,
        "itemInventoryBalance": itemInventoryBalance,
        "itemCommodity": itemCommodity,
        "itemIssueUnit": itemIssueUnit,
        "itemStructure": itemStructure,
        "itemDtPole": itemDtPole,
      };
  @override
  String toString() {
    // TODO: implement toString
    return '$itemNum';
  }
}

Now i'm having a hard time parsing the jsonresponse i got from the api. here's what i got (see comments on the code lines):

Future loadParent2() async {

    Map data = {'wonum': WOInputted};

    var bodyy = json.encode(data);

    var jsonString = await http.post(
        Uri.parse("https://sample.com.ph/extension/list/"),
        headers: {
          'Content-type': 'application/json',
          'Authorization': 'Bearer $getAccessToken'
        },
        body: bodyy);
      
    final jsonResponse = jsonDecode(jsonString.body);
    final valueResponse = jsonResponse['results']['status_code'];
    
    if (jsonString.statusCode == 200 && valueResponse == '1') {
      print('NO RESULTS IN PARENT WO');
      print('VALUE RESPONSE: $valueResponse');
      
     
    } else if (jsonString.statusCode == 200 && valueResponse == '0') {
      print('THIS HAVE RESULTS IN PARENT WO');
      print('VALUE RESPONSE: $valueResponse');
      sampleParentWO = jsonResponse['results']['data']['parentWo'];
      final parentWOResponse = jsonResponse['results']['data'];
      print(parentWOResponse); //CAN PRINT THIS RESPONSE, MEANING I GOT A RIGHT RESPONSE
      
      Data dataPick = new Data.fromJson(parentWOResponse); //NOT SURE IF JSON RESPONSE IS SAVING TO MY MODEL PODO
      print(dataPick.parentWo); //WHEN I TRY TO PRINT THIS THERE'S NO OUTPUT
      mainParentPick = Data.fromJson(parentWOResponse);
      print(mainParentPick.parentWo); //TRIED THIS BUT STILL NO OUTPUT
      print(mainParentPick); //NO OUTPUT
      return mainParentPick;
    }
    
    else {
      throw Exception('Failed there\'s an error');
    }
  }

What am I missing here? do i need to do something else? Hope someone helps me and point to the right direction.

Thank you for your time.

CodePudding user response:

You can use json to dart online tools or can add plugin to Android Studio

  1. One of dart generator online tool - Json Formatter Online Tool
  2. Android Studio Plugin Json2Dart Plugin

CodePudding user response:

I have created a dart model by your Api response from here :

class ApiResponseModel {

 Results? results;

  ApiResponseModel({this.results});

  ApiResponseModel.fromJson(Map<String, dynamic> json) {
    results =
        json['results'] != null ? new Results.fromJson(json['results']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.results != null) {
      data['results'] = this.results!.toJson();
    }
    return data;
  }
}

class Results {
  Data? data;
  String? statusCode;
  String? statusMsg;

  Results({this.data, this.statusCode, this.statusMsg});

  Results.fromJson(Map<String, dynamic> json) {
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
    statusCode = json['status_code'];
    statusMsg = json['status_msg'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.data != null) {
      data['data'] = this.data!.toJson();
    }
    data['status_code'] = this.statusCode;
    data['status_msg'] = this.statusMsg;
    return data;
  }
}

class Data {
  String? parentWo;
  String? parentWoDesc;
  String? parentWoStatus;
  String? parentWoStatusDate;
  String? parentWoWorkType;
  String? parentWoClass;
  String? parentWoCrew;
  String? parentWoLead;
  String? parentWoLocation;
  String? parentWoDepartmentDescription;
  String? parentWoSectionDescription;
  List<Children>? children;

  Data(
      {this.parentWo,
      this.parentWoDesc,
      this.parentWoStatus,
      this.parentWoStatusDate,
      this.parentWoWorkType,
      this.parentWoClass,
      this.parentWoCrew,
      this.parentWoLead,
      this.parentWoLocation,
      this.parentWoDepartmentDescription,
      this.parentWoSectionDescription,
      this.children});

  Data.fromJson(Map<String, dynamic> json) {
    parentWo = json['parentWo'];
    parentWoDesc = json['parentWoDesc'];
    parentWoStatus = json['parentWoStatus'];
    parentWoStatusDate = json['parentWoStatusDate'];
    parentWoWorkType = json['parentWoWorkType'];
    parentWoClass = json['parentWoClass'];
    parentWoCrew = json['parentWoCrew'];
    parentWoLead = json['parentWoLead'];
    parentWoLocation = json['parentWoLocation'];
    parentWoDepartmentDescription = json['parentWoDepartmentDescription'];
    parentWoSectionDescription = json['parentWoSectionDescription'];
    if (json['children'] != null) {
      children = <Children>[];
      json['children'].forEach((v) {
        children!.add(new Children.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['parentWo'] = this.parentWo;
    data['parentWoDesc'] = this.parentWoDesc;
    data['parentWoStatus'] = this.parentWoStatus;
    data['parentWoStatusDate'] = this.parentWoStatusDate;
    data['parentWoWorkType'] = this.parentWoWorkType;
    data['parentWoClass'] = this.parentWoClass;
    data['parentWoCrew'] = this.parentWoCrew;
    data['parentWoLead'] = this.parentWoLead;
    data['parentWoLocation'] = this.parentWoLocation;
    data['parentWoDepartmentDescription'] = this.parentWoDepartmentDescription;
    data['parentWoSectionDescription'] = this.parentWoSectionDescription;
    if (this.children != null) {
      data['children'] = this.children!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Children {
  String? woNum;
  String? woDesc;
  String? woStatus;
  String? woStatusDate;
  String? woCrew;
  String? woLead;
  String? woLocation;
  List<Materials>? materials;

  Children(
      {this.woNum,
      this.woDesc,
      this.woStatus,
      this.woStatusDate,
      this.woCrew,
      this.woLead,
      this.woLocation,
      this.materials});

  Children.fromJson(Map<String, dynamic> json) {
    woNum = json['woNum'];
    woDesc = json['woDesc'];
    woStatus = json['woStatus'];
    woStatusDate = json['woStatusDate'];
    woCrew = json['woCrew'];
    woLead = json['woLead'];
    woLocation = json['woLocation'];
    if (json['materials'] != null) {
      materials = <Materials>[];
      json['materials'].forEach((v) {
        materials!.add(new Materials.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['woNum'] = this.woNum;
    data['woDesc'] = this.woDesc;
    data['woStatus'] = this.woStatus;
    data['woStatusDate'] = this.woStatusDate;
    data['woCrew'] = this.woCrew;
    data['woLead'] = this.woLead;
    data['woLocation'] = this.woLocation;
    if (this.materials != null) {
      data['materials'] = this.materials!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Materials {
  String? itemNum;
  String? itemDescription;
  double? itemQuantityPlan;
  int? itemQuantityIssued;
  double? itemWoBalance;
  double? itemInventoryBalance;
  String? itemCommodity;
  String? itemIssueUnit;
  bool? itemStructure;
  bool? itemDtPole;

  Materials(
      {this.itemNum,
      this.itemDescription,
      this.itemQuantityPlan,
      this.itemQuantityIssued,
      this.itemWoBalance,
      this.itemInventoryBalance,
      this.itemCommodity,
      this.itemIssueUnit,
      this.itemStructure,
      this.itemDtPole});

  Materials.fromJson(Map<String, dynamic> json) {
    itemNum = json['itemNum'];
    itemDescription = json['itemDescription'];
    itemQuantityPlan = json['itemQuantityPlan'];
    itemQuantityIssued = json['itemQuantityIssued'];
    itemWoBalance = json['itemWoBalance'];
    itemInventoryBalance = json['itemInventoryBalance'];
    itemCommodity = json['itemCommodity'];
    itemIssueUnit = json['itemIssueUnit'];
    itemStructure = json['itemStructure'];
    itemDtPole = json['itemDtPole'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['itemNum'] = this.itemNum;
    data['itemDescription'] = this.itemDescription;
    data['itemQuantityPlan'] = this.itemQuantityPlan;
    data['itemQuantityIssued'] = this.itemQuantityIssued;
    data['itemWoBalance'] = this.itemWoBalance;
    data['itemInventoryBalance'] = this.itemInventoryBalance;
    data['itemCommodity'] = this.itemCommodity;
    data['itemIssueUnit'] = this.itemIssueUnit;
    data['itemStructure'] = this.itemStructure;
    data['itemDtPole'] = this.itemDtPole;
    return data;
  }
}

Step 2 : create function for calling api

Future<http.Response> getResponse(Map<String, String> request) async {
 final response =
  await http.post(Uri.parse(BASE_URL   "urlapilink"), body: request.toJson());
  return response;
}

step 3 : get response from api :

ApiResponseModel apiResponseModel ; 
       getResponseFromApi(){
        Map request = {'wonum': WOInputted};
        getFirmDetails(request).then((value){
          if(value.statusCode==200){
     apiResponseModel  = ApiResponseModel.fromJson(value.body);
    }
        });
      }

CodePudding user response:

There is casting error with your json response and response model

In your model, Type cast using Int.

int? itemQuantityPlan;
int? itemQuantityIssued;
int? itemWoBalance;

In your Response, There is double

  "itemQuantityPlan": 1.0,
  "itemQuantityIssued": 42.0,
  "itemWoBalance": -41.0,
  "itemInventoryBalance": -2602.47,
  • Related