Parsing dynamic json values in Flutter

48 views Asked by At

In my flutter application, I am receiving json response and can also able to parse it easily. But At a point or a key named "data" in json response giving me dynamic value as below:

Sometime it coming like (1):

"data": {
                "count": "237",
                "dollars": "279370.62"
            },

Sometime it coming like (2):

"data": 122093.43,

Sometime it coming like (3):

"data": {
                "colas": 4,
                "formulas": 0
            },

and Sometime it coming like (4):

"data": "122093.43",

So How can I decide that whether is it a normal String value inside json or I need to parse a data object? and you might also noticed that the keys inside data is also getting changed.

What is the best way to handle this?

2

There are 2 answers

0
Jaimin Modi On BEST ANSWER

With the use of type dynamic we can solve this issue and then using JsonDecode functionality its easy to get values for the required json keys.

1
Rodrigo Molero On

You just have to map every possible outcome for your response... one way to do it is to iterate for keys in your map, but I think that would be kind of complex because you'll have to add extra logic once data has been retreived and not handled before that. I would so something like this:

class CustomDataObject {
  String? count;
  String? formulas;
  String? dollars;
  double? doubleData; //Change for something more readable
  String? stringData; //Change for something more readable
  
  //... add more values if needed

  CustomDataObject({
    this.count,
    this.formulas,
    this.dollars,
    this.doubleData,
    this.stringData,
  });
  
  factory CustomDataObject.fromJson (dynamic json) {
    if (json is Map<String, dynamic>) {
      return CustomDataObject(
        count: json['count'],
        formulas: json['formulas'],
        dollars: json['dollars']
      );
    }
    
    if (json is String) {
      return CustomDataObject(
        stringData: json
      );
    }
    
    if (json is double) {
      return CustomDataObject(
        doubleData: json
      );
    }
    
    // Add more statements according to your needs
    
    // Return empty object if non of the cases
    return CustomDataObject();
  }
}

With the code above you can handle your incoming data based on its type and work with its properties. Btw, using if statements here is fine, it makes the code more readable IMO