How to properly process the response?

Viewed 28

I understand how to process data when an array of objects comes in, but how can I process the response if I receive data in the form -

{
  "camera": "108+12mp",
    "capacity": [
      "126",
      "252"
   ],
}

Here is how I created the model and entity for the view data - data -

"homestore": [
    {
      "id": 1,
      "is_new": true,
      "title": "Iphone 12",
      "subtitle": "Super. Mega. Rápido.",
      "picture": "https://img.ibxk.com.br/2020/09/23/23104013057475.jpg?w=1120&h=420&mode=crop&scale=both",
      "is_buy" : true
    },

Entity -

class HotSalesEntity extends Equatable{
  final int id;
  final isNew;
  final String title;
  final String subTitle;
  final String picture;
//Создаем конструктор
  const HotSalesEntity({
    required this.id,
    required this.isNew,
    required this.title,
    required this.subTitle,
    required this.picture
  });
  //Props для Equatable, чтобы можно было легко сравнивать данные
  @override
  // TODO: implement props
  List<Object?> get props => [id, isNew, title, subTitle, picture];
}

request + parsing -

Future<List<HotSalesModel>> getAllHotSales() async {
final response = await client.get(
    Uri.parse(ConfigUrl.home),
    headers: {'Content-Type': 'application/json'}
    );
if(response.statusCode == 200) {
  final hotSales = json.decode(response.body);
  print('Data in server: $hotSales');
  return (hotSales['home_store'] as List).map((e) => HotSalesModel.fromJson(e)).toList();
} else {
  throw ServerException();
}
}

And model -

class HotSalesModel extends HotSalesEntity{
  HotSalesModel({
    required id,
    required isNew,
    required title,
    required subTitle,
    required picture
}) : super(
    id: id,
    isNew: isNew,
    title: title,
    subTitle: subTitle,
    picture: picture
  );

  factory HotSalesModel.fromJson(Map<String, dynamic> json) {
    return HotSalesModel(
        id: json['id'],
        isNew: json['is_new'],
        title: json['title'],
        subTitle: json['subtitle'],
        picture: json['picture']
    );
  }

Sorry I provided too much code, I'm just a beginner and don't really understand what you need for the example. I think it would be great if you could make a small example, kind of like mine, but only for the data

I can't figure out how I can process such a response from the server, I would sincerely appreciate any help!

1 Answers

You can skip it. change this:

 return (hotSales['home_store'] as List).map((e) => HotSalesModel.fromJson(e)).toList();

to :

    List result = [];
    for (var element in hotSales['home_store'] as List) {
      if (element['id'] != null) {
        reult.add(HotSalesModel.fromJson(element));
      }
    }

    return result;
Related