【问题标题】:JSON Parse not parsing in Flutter if some object is empty如果某些对象为空,则 JSON Parse 不会在 Flutter 中解析
【发布时间】:2020-08-17 13:10:22
【问题描述】:

我有一个注册表单,后端是 PHP。 PHP 返回成功,错误数据为 JSON。

下面是我的 JSONParse 文件。

import 'dart:convert';

Signup signupFromJson(String str) => Signup.fromJson(json.decode(str));

String signupToJson(Signup data) => json.encode(data.toJson());

class Signup {
    Errors errors;
    bool success;

    Signup({
        this.errors,
        this.success,
    });

    factory Signup.fromJson(Map<String, dynamic> json) => Signup(

        errors: Errors.fromJson(json["errors"]),
        success: json["success"],
    );

    Map<String, dynamic> toJson() => {
        "errors": errors.toJson(),  
        "success": success,
    };
}

class Errors {
    String password1;
    String email1;
    String name;

    Errors({
        this.password1,
        this.email1,
        this.name,
    });

    factory Errors.fromJson(Map<String, dynamic> json) => Errors(
        password1: json["Password1"],
        email1: json["Email1"],
        name: json["Name"],
    );

    Map<String, dynamic> toJson() => {
        "Password1": password1,
        "Email1": email1,
        "Name": name,
    };
}

这是示例 JSON 数据。

如果由于不满足某些条件而导致登录失败。

{"errors":{"Email1":"Email could not be empty",
"Password1":"Password could not be empty",
"Name":"Your name must be between 3 to 30 characters!"},
"success":false}

如果登录成功

{"success":false}

如果条件不满足,我的 JSONParse 工作正常。我的意思是它重新调整所有错误和成功错误。

但是如果登录成功则它不起作用,通过检查更多我发现来自 PHP 的数据很好。

Signup signupFromJson(String str) => Signup.fromJson(json.decode(str)); - Data is coming in str variable.

factory Signup.fromJson(Map<String, dynamic> json) => Signup(

            errors: Errors.fromJson(json["errors"]), -- If error is nulll then it is not checking the success.
            success: json["success"],
        );

错误为空时出现的问题然后移出并没有转到成功部分。

我在这里做错了什么?

【问题讨论】:

  • 你为什么不添加一个像json["errors"] ?? ""这样的条件,这将检查值并返回“”如果值为空
  • @VickySalunkhe 感谢您希望我添加的评论。
  • 您添加评论的行If error is nulll then it is not checking the success.
  • 我试过这个错误:Errors.fromJson(json["errors"] ?? null),但它仍然无法正常工作。它仍在跳过成功。
  • 也看看这个,我已经发了一个适合这里的答案(如果你期待如何处理json)stackoverflow.com/a/58708634/9236994

标签: json flutter


【解决方案1】:

如果你成功了,那么你就不会出错,所以你必须检查 null 知道你在哪里传递给错误类。

在 Signup.fromJson 中:

 errors: Errors.fromJson(json["errors"] ?? {}),

在错误类中

 factory Errors.fromJson(Map<String, dynamic> json) => Errors(
        password1: json["Password1"] ?? '',
        email1: json["Email1"] ?? '',
        name: json["Name"] ?? '',
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-14
    • 2021-05-17
    • 2022-01-09
    • 2012-07-28
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多