Roxx
Roxx

Reputation: 3986

Flutter : JSON.parse fail on empty string

I am trying to parse JSON data in Flutter and it is working fine. But when some data is empty or null then it is not working and giving error.

import 'dart:convert';

GetFollowing getFollowingFromJson(String str) => GetFollowing.fromJson(json.decode(str));

class GetFollowing {
    List<Content> content;
    int count;
    bool success;
    String error;

    GetFollowing({
        this.error,
        this.content,
        this.count,
        this.success,
    });

    factory GetFollowing.fromJson(Map<String, dynamic> json) => GetFollowing(
        error: json["error"],
        content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
        count: json["count"],
        success: json["success"],
    );

}

class Content {
    int uid;
    int following;
    String name;
    String profilePhoto;
    String baseLocation;
    String registrationDate;
    String country;

    Content({
        this.uid,
        this.following,
        this.name,
        this.profilePhoto,
        this.baseLocation,
        this.registrationDate,
        this.country,
    });

    factory Content.fromJson(Map<String, dynamic> json) => Content(
        uid: json["uid"] ?? null,
        following: json["following"] ?? null,
        name: json["name"] ?? null,
        profilePhoto: json["profile_photo"] ?? null,
        baseLocation: json["base_location"] ?? null,
        registrationDate: json["registration_date"] ?? null,
        country: json["country"] ?? null,
    );

}

Here is the sample data.

  1. Scenario

    {"error":"No record found.","success":false}

  2. Scenario

{
    "content": [{
        "uid": 34,
        "following": 35,
        "name": "Sadi",
        "profile_photo": "noimage.png",
        "base_location": "New Delhi",
        "registration_date": "03-05-2020",
        "country": "India"
    }, {
        "uid": 34,
        "following": 37,
        "name": "Sameer",
        "profile_photo": "noimage.png",
        "base_location": "New Delhi",
        "registration_date": "03-05-2020",
        "country": "India"
    }, {
        "uid": 34,
        "following": 36,
        "name": "Simran",
        "profile_photo": "noimage.png",
        "base_location": "New Delhi",
        "registration_date": "03-05-2020",
        "country": "India"
    }],
    "count": 3,
    "success": true
}

I am getting error if content is null or empty then parse didn't complete and gives error.

Exception Caught: NoSuchMethodError: The method '[]' was called on null.

Upvotes: 1

Views: 1178

Answers (1)

Adam Jenkins
Adam Jenkins

Reputation: 55613

content: (json["content"] as List).map((x as Map<String, dynamic>) => Content.fromJson(x)).toList()

Consider json_annotation or built_value to handle all your boiler plate for you.

Upvotes: 1

Related Questions