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"
        },
    ]
1
  • If you know YAML, then you can describe your model using YAML and then generate the necessary code. stackoverflow.com/a/66464998/1737201 Commented Jul 24, 2022 at 19:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.