0

I am having some difficulties with parsing the JSON from API. Previously the JSON format was simpler:

        {   "author": {
                "id": 4,
                "username": "maria"
             },
            "description": "dsada",
            "image": "/media/posts/image_cropper_1616320457204.jpg",
            "created_at": "2021-03-21T09:54:38.645596Z"
        },
        {
            "author": {
                "id": 4,
                "username": "maria"
            },
            "description": "asdsad",
            "image": "/media/posts/image_cropper_1616070403137.jpg",
            "created_at": "2021-03-18T12:26:56.774797Z"
        }

And my model for that JSON format was the following

class Feed {
  final String author;
  final String description;
  final String imageUrl;
  final String createdAt;

  Feed({this.author, this.description, this.imageUrl, this.createdAt});

  factory Feed.fromJson(Map<String, dynamic> json) {
    return Feed(
      author: json['author']['username'],
      description: json['description'],
      imageUrl: json['image'],
      createdAt: json['created_at'],
    );
  }
}

Recently the API was changed slightly to enable pagination. After that the I couldn't figure out a way to properly get that data from API in a correct format. New JSON format looks like this:

{
  'count: 6,
  'next': "/posts/list/?limit=5&offset=5",
  'previous': null,'
  'results': [
      {   "author": {
                "id": 4,
                "username": "maria"
             },
            "description": "dsada",
            "image": "/media/posts/image_cropper_1616320457204.jpg",
            "created_at": "2021-03-21T09:54:38.645596Z"
        },
        {
            "author": {
                "id": 4,
                "username": "maria"
            },
            "description": "asdsad",
            "image": "/media/posts/image_cropper_1616070403137.jpg",
            "created_at": "2021-03-18T12:26:56.774797Z"
        }
   ]
   
}

I didn't think that after adding pagination the JSON format would change. If you have any idea to do this, kindly help. Thank you.

1 Answer 1

2

To create your classes quickly you can use this application that could help you in the beginning, then you can make the modifications if necessary. (https://app.quicktype.io/)

class User {
    User({
        this.count,
        this.next,
        this.previous,
        this.results,
    });

    final int count;
    final String next;
    final dynamic previous;
    final List<Result> results;

    factory User.fromJson(Map<String, dynamic> json) => User(
        count: json["count"],
        next: json["next"],
        previous: json["previous"],
        results: List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "count": count,
        "next": next,
        "previous": previous,
        "results": List<dynamic>.from(results.map((x) => x.toJson())),
    };
}


class Result {
    Result({
        this.author,
        this.description,
        this.image,
        this.createdAt,
    });

    final Author author;
    final String description;
    final String image;
    final DateTime createdAt;

    factory Result.fromJson(Map<String, dynamic> json) => Result(
        author: Author.fromJson(json["author"]),
        description: json["description"],
        image: json["image"],
        createdAt: DateTime.parse(json["created_at"]),
    );

    Map<String, dynamic> toJson() => {
        "author": author.toJson(),
        "description": description,
        "image": image,
        "created_at": createdAt.toIso8601String(),
    };
}

class Author {
    Author({
        this.id,
        this.username,
    });

    final int id;
    final String username;

    factory Author.fromJson(Map<String, dynamic> json) => Author(
        id: json["id"],
        username: json["username"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "username": username,
    };
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. But in this case how do I get the data inside Feed screen ? With my previous code I was getting it through List<Feed> feeds = await DatabaseService.getPosts(); since they were all in one format.
@Davrick First of all in the solution that I provide you could modify the class name from Author to Feed. After doing that and if I implement the other classes as recommended, it will no longer receive a List of type Feed (List<Feed>), but rather an instance of type Feed (Feed), which then in the widget you can invoke the list as follows: Feed.results

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.