Home > other >  Check if key exists in a json array
Check if key exists in a json array

Time:03-10

I have a service that returns a json array which parse and map into a list of an object that I have created . The problem is that I have a key called "productName" which is not returned with json response when it doesn't contain a value. What I what I want to do is parse the json array and for every item in the array test if the key is there or not , if so I should return the value of the key if not I return a default value to the field productName I have created in my model .

This is my service :

Future<List<Qrqc>?> fetchMyQrqc(
      {required String baseUrl, required String id}) async {
    try {
      http.Response response = await http.get(
        Uri.parse(
            "https://demo.app.deepnrise.com/api-qrqc/qrqc/v1/qrqc/myqrqc/?userId=b0862e0e-ffe7-48c5-8f3c-3307b7f0671e&page=1&pageSize=1000000"),
        headers: {HttpHeaders.contentTypeHeader: 'application/json'},
      );

      if (response.statusCode == 200) {
        var codeUnits = response.body.codeUnits;
        var responseParsed = const Utf8Decoder().convert(codeUnits);
        List<Qrqc> myQRQC = (json.decode(responseParsed) as List)
            .map((data) => Qrqc.fromJson(data))
            .toList();

        debugPrint("List Qrqc fetched with success");

        return myQRQC;
      } else {
        throw Exception('Failed to load qrqc');
      }
    } catch (ex) {
      debugPrint(ex.toString());
    }
  }


This is my model :

import 'dart:convert';

Qrqc qrqc(String str) => Qrqc.fromJson(json.decode(str));

class Qrqc {
  // ignore: non_constant_identifier_names
  Qrqc(
      {required this.id,
      this.title,
      this.progress,
      this.status,
      this.role,
      this.createdAt,
      this.perimeterName,
      this.typeID, this.productName});
  // ignore: non_constant_identifier_names
  int id;
  String? title;
  int? progress;
  String? role;
  String? status;
  String? typeID;
  String? createdAt;
  String? perimeterName;
  String? productName;
  String? typeName;

  factory Qrqc.fromJson(Map<String, dynamic> json) {
    return Qrqc(
      id: json['id'],
      progress: json["progress"],
      role: json["role"],
      status: json["status"],
      title: json["title"],
      createdAt: json["detectedAt"],
      perimeterName: json["perimeterName"],
      typeID: json["typeID"],
      productName: json["productName"],
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = id;
    data['progress'] = progress;
    data['role'] = role;
    data['status'] = status;
    data['perimeterName'] = perimeterName;
    data['detectedAt'] = createdAt;
    data['typeID'] = title;
    data['productName'] =  productName;
    return data;
  }
}
 



For now the service is returning a null exception because as I said some items in the json array contain the key while others don't . I want to be able to keep the field in my model , parse the json array and test if every item contain the key or not . I know there's a method in dart containsKey but I didn't know where or how to use it on json array not a simple model of json. If anyone can help I'd be grateful .

CodePudding user response:

You can use a simple null check on the json fields using the ?? operator with a default. Use it like

productName: json["productName"] ?? 'Default Product Name';

That should automatically set the default value Default Product Name if the JSON field is null.

It's essentially a short hand for

productName: json["productName"] != null ? json["productName"] : 'Default Product Name';
  • Related