映射嵌套 JSON 时如何检查 NULL?

Hoo*_*yar 8 json dart flutter

我正在尝试将嵌套的 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",
                    }
                    ]
}
]
Run Code Online (Sandbox Code Playgroud)

映射到对象的代码:

  featuredMediaUrl = map ["_embedded"]["wp:featuredmedia"][0]["source_url"];
Run Code Online (Sandbox Code Playgroud)

'map' 方法在 null 上被调用。接收者: null [0] 有时返回 null ;

sha*_*eep 9

按照我的评论,我建议您使用代码生成库来解析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);
}
Run Code Online (Sandbox Code Playgroud)

使用 ( 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
Run Code Online (Sandbox Code Playgroud)

请注意这里的 cli 参数--all-properties-optional,该参数为缺失的字段创建空检查。

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(),
};
Run Code Online (Sandbox Code Playgroud)

然后我使用了 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());
Run Code Online (Sandbox Code Playgroud)

一切都很顺利。

注意 当然,当你使用这个类时,你必须在使用它们之前检查它的字段是否为空:

print(exampleClass.embedded?.wpFeaturedmedia?.toString());
Run Code Online (Sandbox Code Playgroud)

就这样。我希望已经把你放在正确的方向上。


Eli*_*iss 5

这是一个简单的解决方案:

safeMapSearch(Map map, List keys) {
  if (map[keys[0]] != null) {
    if (keys.length == 1) {
      return map[keys[0]];
    }
    List tmpList = List.from(keys);
    tmpList.removeAt(0);
    return safeMapSearch(map[keys[0]], tmpList);
  }
  return null;
}
Run Code Online (Sandbox Code Playgroud)

使用:

featuredMediaUrl = safeMapSearch(map, ["_embedded","wp:featuredmedia",0,"source_url"]);
Run Code Online (Sandbox Code Playgroud)

map该函数使用 中提供的键递归地迭代keys,如果缺少某个键,它将返回null,否则它将返回最后一个键的值。