0

I have such a list returned from the server, I couldn't find how to create an object model for it? Can you help me?

[ 
        {
            "id": 1,
            "reason": "Adres Sorunu Nedeniyle Alıcıya Ulaşılmadı"
        },
        {
            "id": 2,
            "reason": "Alıcı Adresinde Yok - Notlu Kargo"
        },
    ]
VolkanUstekidag
  • 345
  • 2
  • 8
  • If you know YAML, then you can describe your model using YAML and then generate the necessary code. https://stackoverflow.com/a/66464998/1737201 – mezoni Jul 24 '22 at 19:25

1 Answers1

1

Here is a small example of how to make a model of this JSON structure:

import 'dart:convert';

class MyJsonObject {
  int id;
  String reason;

  MyJsonObject({
    required this.id,
    required this.reason,
  });

  factory MyJsonObject.fromJson(Map<String, dynamic> jsonMap) => MyJsonObject(
        id: jsonMap['id'] as int,
        reason: jsonMap['reason'] as String,
      );

  Map<String, Object> toJson() => {
        'id': id,
        'reason': reason,
      };

  @override
  String toString() => '{ID: $id, Reason: $reason}';
}

void main() {
  String jsonString = '''[
  {
    "id": 1,
    "reason": "Adres Sorunu Nedeniyle Alıcıya Ulaşılmadı"
  },
  {
    "id": 2,
    "reason": "Alıcı Adresinde Yok - Notlu Kargo"
  }
]
''';

  List<dynamic> jsonList = jsonDecode(jsonString) as List<dynamic>;

  List<MyJsonObject> myObjects = [
    for (final jsonMap in jsonList)
      MyJsonObject.fromJson(jsonMap as Map<String, dynamic>)
  ];

  myObjects.forEach(print);
  // {ID: 1, Reason: Adres Sorunu Nedeniyle Alıcıya Ulaşılmadı}
  // {ID: 2, Reason: Alıcı Adresinde Yok - Notlu Kargo}
}

I recommend reading the following if you need to handle more complicated data structures: https://docs.flutter.dev/development/data-and-backend/json

julemand101
  • 28,470
  • 5
  • 52
  • 48