首页 > 解决方案 > 映射嵌套 JSON 时如何检查 NULL?

问题描述

我正在尝试将嵌套的 JSON 映射到模型对象,问题是当它返回 null 时,它会破坏所有代码,我想检查 null 是否做某事但不破坏应用程序。

JSON文件:

[
    {
        "id": 53,
        "date": "2018-12-28T08:51:11",
        "title": {
            "rendered": "this is for featured"
        },
        "content": {
            "rendered": "\n<p><g class=\"gr_ gr_3 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling\" id=\"3\" data-gr-id=\"3\">sdafkj</g> <g class=\"gr_ gr_10 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace\" id=\"10\" data-gr-id=\"10\">kj</g> <g class=\"gr_ gr_16 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace\" id=\"16\" data-gr-id=\"16\">asd</g> <g class=\"gr_ gr_18 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling\" id=\"18\" data-gr-id=\"18\">kadjsfk</g> kljadfklj sd</p>\n",
            "protected": false
        },
        "excerpt": {
            "rendered": "<p>sdafkj kj asd kadjsfk kljadfklj sd</p>\n",
            "protected": false
        },
        "author": 1,
        "featured_media": 54,
        "_links": {
            "self": [
                {
                    "href": "https://client.kurd.app/wp-json/wp/v2/posts/53"
                }
            ],

        },
        "_embedded": {
            "author": [
                {
                    "id": 1,
                    "name": "hooshyar",

                }
            ],
            "wp:featuredmedia": [
                {
                    "id": 54,

                    "source_url": "https://client.kurd.app/wp-content/uploads/2018/12/icannotknow_22_12_2018_18_48_11_430.jpg",
                    }
                    ]
}
]

映射到对象的代码:

  featuredMediaUrl = map ["_embedded"]["wp:featuredmedia"][0]["source_url"];

在 null 上调用了方法“map”。Receiver: null [0] 有时返回 null ;

标签: jsondartflutter

解决方案


根据我的评论,我建议您使用代码生成库解析JSONJSON Models.

阅读这篇文章,了解如何使用(例如)json_serializable包。

此类库承担了生成所有样板代码以创建模型类的所有繁琐工作,并且它们将null值视为强制性或非强制性的。

例如,如果您这样注释类 Person :

@JsonSerializable(nullable: true)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

使用 ( nullable: true) 模型的 dart 类将跳过空值字段。

在此处输入图像描述

更新

因为我渴望技术,所以我给了quicktype工具(由 Christoph Lachenicht 建议)尝试使用您的示例。

我准备了一个模拟 api和一个example.json提供您发布的 JSON 的文件。我只取了一个元素,而不是数组。您可以在这里查看example.json

安装 QuickType 后,我为这个 json 生成了模型类:

quicktype --lang dart --all-properties-optional example.json -o example.dart

请注意此处--all-properties-optional为缺失字段创建空检查的 cli 参数。

Map<String, dynamic> toJson() => {
    "id": id == null ? null : id,
    "date": date == null ? null : date,
    "title": title == null ? null : title.toJson(),
    "content": content == null ? null : content.toJson(),
    "excerpt": excerpt == null ? null : excerpt.toJson(),
    "author": author == null ? null : author,
    "featured_media": featuredMedia == null ? null : featuredMedia,
    "_links": links == null ? null : links.toJson(),
    "_embedded": embedded == null ? null : embedded.toJson(),
};

然后我使用了 Example 类example.dart

var jsonExampleResponse =
    await http.get('https://www.shadowsheep.it/so/53962129/testjson.php');
print(jsonExampleResponse.body);

var exampleClass = exampleFromJson(jsonExampleResponse.body);
print(exampleClass.toJson());

一切顺利。

注意 当然,当您使用此类时,您必须在使用它们之前检查其字段是否为空:

print(exampleClass.embedded?.wpFeaturedmedia?.toString());

就这样。我希望能把你引向正确的方向。


推荐阅读