Parse json content inside nested key

Viewed 48

I'm new to Flutter/Dart and I'm trying to parse this json:

{
  "item": {
    "array1": [
      {
        "key1": "value1",
        "key2": "value2"
      }
    ],
    "array2": [
      {
        "key1": "value1",
        "key2": "value2"
      }
    ],
  }
}

I've created two models, one for the single element of the list:

class Model {
  final String key1;
  final String key2;

  const Lineup({
    required this.key1,
    required this.key2
  });

  factory Model.fromJson(Map<String, dynamic> json) {
    return Model(
        key1: json['key1'] as String,
        key2: json['key2'] as String
  }
}

And one for the whole server response:

class ModelResponse {
  final List<Model> array1;
  final List<Model> array2;

  const ModelResponse({
    required this.array1,
    required this.array2,
  });

  factory ModelResponse.fromJson(Map<String, dynamic> json) {
    return ModelResponse(
        array1: (json['array1'])
            .map((i) => Model.fromJson(i) as List) --> TYPO HERE
            .toList(),
        array2: (json['array2'] as List)
            .map((i) => Model.fromJson(i))
            .toList());
  }
}

I'm calling:

var jsonResponse = jsonDecode(response.body);
return ModelResponse.fromJson(jsonResponse['item']);

but I'm getting:

type 'Model' is not a subtype of type List< dynamic > in type cast

How should i cast the whole response? Thanks in advance.

EDIT: there was a typo in the cast "as List" goes 1 line up.

1 Answers

Here is my trial.

  • Change constructor name in Model class
  • Add prefix after map method.
  • Remove 'as List' in array1 map inside.

class Model {
  final String key1;
  final String key2;

  const Model({
    required this.key1,
    required this.key2
  });

  factory Model.fromJson(Map<String, dynamic> json) {
    return Model(
        key1: json['key1'] as String,
        key2: json['key2'] as String
    );
  }
}
   
   
class ModelResponse {
  final List<Model> array1;
  final List<Model> array2;

  const ModelResponse({
    required this.array1,
    required this.array2,
  });

  factory ModelResponse.fromJson(Map<String, dynamic> json) {
    return ModelResponse(
        array1: (json['array1'] as List)
            .map<Model>((i) => Model.fromJson(i))
            .toList(),
        array2: (json['array2'] as List)
            .map<Model>((i) => Model.fromJson(i))
            .toList());
  }
}
Related