json - 将 JSON 字符串映射到 FLUTTER 中的项目模型

标签 json dart flutter

在此项目中,应用程序以 JSON 形式从 WP REST API 接收帖子,它工作正常,但我需要将其转换为项目模型(用于缓存和数据库):所以我创建了一个项目模型,现在如何我在我的代码中实现它,它获取 String.如何在 getPosts() 中映射我的数据,以便它返回一个帖子,而不是一个字符串?请告诉我代码中的方法。

// Function to get list of posts which is String
 Future<String> getPosts() async {
 var res = await http.get(Uri.encodeFull(apiUrl + "posts?_embed&per_page=10"),
 headers: {"Accept": "application/json"});
 setState(() {
 var resBody = json.decode(res.body);

 posts = resBody;
});

return "Success!";
}

future builder 将在加载帖子之前显示加载指示器:

 body: FutureBuilder<List<String>>(
  future: getPosts(),
  builder: (context, snapshot) {
    if (snapshot.hasError) print(snapshot.error);

    return snapshot.hasData
        ? ListViewPosts(posts: snapshot.data)
        : Center(child: CircularProgressIndicator());
  },
),

ItemModel 代码

class Post {
  int _id;
  String _title;
  String _content;
  String _author;
  String _date;
  String _imgUrl;

  Post(this._id, this._title, this._content, this._author, this._date,
      [this._imgUrl]);

  Post.withId(this._id, this._title, this._content, this._author, this._date,
      [this._imgUrl]);

  int get id => _id;
  String get title => _title;
  String get content => _content;
  String get author => _author;
  String get date => _date;
  String get imgUrl => _imgUrl;

  set title(String newTitle) {
    this._title = newTitle;
  }

  set content(String newContent) {
    this._content = newContent;
  }

  set author(String newAuthor) {
    this._author = newAuthor;
  }

  set date(String newDate) {
    this._date = newDate;
  }

  set imgUrl(String newImgUrl) {
    this._imgUrl = newImgUrl;
  }

  //convert post to Map
  Map<String, dynamic> toMap() {
    var map = Map<String, dynamic>();

    if (id != null) {
      map['id'] = _id;
    }
    map['title'] = _title;
    map['content'] = _content;
    map['author'] = _author;
    map['date'] = _date;
    map['imgurl'] = _imgUrl;
    return map;
  }

  //Extract post from Map Object
  Post.fromMapObject(Map<String, dynamic> map) {
    this._id = map['id'];
    this._title = map['title'];
    this._content = map['content'];
    this._author = map['author'];
    this._date = map['date'];
    this._imgUrl = map['imgurl'];
  }
}

JSON 响应

{ 
     "id": 73331,
    "date": "2018-11-24T19:00:21",
    "date_gmt": "2018-11-24T19:00:21",
    "guid": {
        "rendered": "theUrl?p=73331"
    },
    "modified": "2018-11-24T19:00:21",
    "modified_gmt": "2018-11-24T19:00:21",
    "slug": "%d8%aa%db%8e%d8%b3%d8%aa-%d8%a8%d9%88-%d9%be%d9%87%e2%80%8c%da%95%db%8c-%d8%b3%d9%87%e2%80%8c%d8%b1%d9%87%e2%80%8c%d9%83%db%8c",
    "status": "publish",
    "type": "post",
    "link": "theUrl/2018/11/24/%d8%aa%db%8e%d8%b3%d8%aa-%d8%a8%d9%88-%d9%be%d9%87%e2%80%8c%da%95%db%8c-%d8%b3%d9%87%e2%80%8c%d8%b1%d9%87%e2%80%8c%d9%83%db%8c/",
    "title": {
        "rendered": "تێست بو په\u200cڕی سه\u200cره\u200cكی"
    },
    "content": {
        "rendered": "<p>تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی</p>\n<div class=\"likebtn_container\" style=\"\"><!-- LikeBtn.com BEGIN --><span class=\"likebtn-wrapper\"  data-identifier=\"post_73331\"  data-theme=\"large\"  data-lang=\"ck\"  data-ef_voting=\"buzz\"  data-tooltip_enabled=\"false\"  data-white_label=\"true\"  data-rich_snippet=\"true\"  data-popup_disabled=\"true\"  data-style=\"\"  data-unlike_allowed=\"\"  data-show_copyright=\"\"  data-item_url=\"theUrl/2018/11/24/%d8%aa%db%8e%d8%b3%d8%aa-%d8%a8%d9%88-%d9%be%d9%87%e2%80%8c%da%95%db%8c-%d8%b3%d9%87%e2%80%8c%d8%b1%d9%87%e2%80%8c%d9%83%db%8c/\"  data-item_title=\"تێست بو په\u200cڕی سه\u200cره\u200cكی\"  data-item_image=\"theUrl/wp-content/uploads/2018/11/IMG_5203-1024x620.jpg\"  data-item_date=\"2018-11-24T19:00:21+00:00\"  data-engine=\"WordPress\"  data-plugin_v=\"2.6.11\"  data-event_handler=\"likebtn_eh\" ></span><!-- LikeBtn.com END --></div>",
        "protected": false
    },
    "excerpt": {
        "rendered": "<p>تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی تێست بو په\u200cڕی سه\u200cره\u200cكی</p>\n<div class=\"likebtn_container\" style=\"\"><!-- LikeBtn.com BEGIN --><span class=\"likebtn-wrapper\"  data-identifier=\"post_73331\"  data-theme=\"large\"  data-lang=\"ck\"  data-ef_voting=\"buzz\"  data-tooltip_enabled=\"false\"  data-white_label=\"true\"  data-rich_snippet=\"true\"  data-popup_disabled=\"true\"  data-style=\"\"  data-unlike_allowed=\"\"  data-show_copyright=\"\"  data-item_url=\"theUrl/2018/11/24/%d8%aa%db%8e%d8%b3%d8%aa-%d8%a8%d9%88-%d9%be%d9%87%e2%80%8c%da%95%db%8c-%d8%b3%d9%87%e2%80%8c%d8%b1%d9%87%e2%80%8c%d9%83%db%8c/\"  data-item_title=\"تێست بو په\u200cڕی سه\u200cره\u200cكی\"  data-item_image=\"theUrl/wp-content/uploads/2018/11/IMG_5203-1024x620.jpg\"  data-item_date=\"2018-11-24T19:00:21+00:00\"  data-engine=\"WordPress\"  data-plugin_v=\"2.6.11\"  data-event_handler=\"likebtn_eh\" ></span><!-- LikeBtn.com END --></div>",
        "protected": false
    },
    "author": 1,
    "featured_media": 73332,
    "comment_status": "open",
    "ping_status": "open",
    "sticky": false,
    "template": "",
    "format": "standard",
    "meta": [],
    "categories": [
        1
    ],
    "tags": [],
    "acf": [],
    "_links": {
        "self": [
            {
                "href": "theUrl/wp-json/wp/v2/posts/73331"
            }
        ],
        "collection": [
            {
                "href": "theUrl/wp-json/wp/v2/posts"
            }
        ],
        "about": [
            {
                "href": "theUrl/wp-json/wp/v2/types/post"
            }
        ],
        "author": [
            {
                "embeddable": true,
                "href": "theUrl/wp-json/wp/v2/users/1"
            }
        ],
        "replies": [
            {
                "embeddable": true,
                "href": "theUrl/wp-json/wp/v2/comments?post=73331"
            }
        ],
    }

最佳答案

您很可能想要使用序列化库。在运行 Flutter 的 Dart 中,常见的一个是 json_serializable .

示例

第 1 步

我以他们的例子作为引用:

Given a library example.dart with an Person class annotated with @JsonSerializable():

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable(nullable: false)
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);
}

请注意,在 dart 文件中,g.dart 中的后缀是由 build system 生成的.

第 2 步

Convert to map

import 'dart:convert';
...
Map valueMap = json.decode(value);

第3步

Deserialize

Person person = Person.from(valueMap)

安装

要安装,只需将其添加到 pubspec.yml 中即可:

dependencies:
  ...
  json_annotation: ^1.2.0

dev_dependencies:
  build_runner: ^0.10.3

然后运行flutter packages get

关于json - 将 JSON 字符串映射到 FLUTTER 中的项目模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53503644/

相关文章:

javascript - 如何从 json 输入中删除空值

java - 如何获取JSONObject的元素?

flutter - 如何使用flutter在Web View 中打开pdf文档

testing - 第一次编译 flutter_driver 时出错

flutter - Dart future 阻塞主线程

java - 在不同服务器上运行的两个 Java Web 应用程序之间传输数据的最佳方式

java - 在android中解析JSON显示不匹配错误

dart - Dart 中 "const"关键字的用途是什么?

dart - 如何在 flutter 中为下拉菜单设置初始值?

dart - Dart WebComponent上不允许使用绝对路径