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

时间:2018-11-27 16:05:19

标签: json dart flutter

在此Project App中,以JSON形式从WP REST API接收帖子,它工作正常,但是我需要将其转换为Item Model(用于缓存和DB):所以我创建了Item-Model,现在如何我在获取String的代码中实现了它。如何在getPosts()中映射我的数据,使其返回Post,而不是String?请,请向我展示CODE中的方式。

// 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!";
}

未来构建器在加载帖子之前显示“加载中”指示符:

 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"
            }
        ],
    }

2 个答案:

答案 0 :(得分:1)

您很可能希望使用序列化库。在运行Flutter的dart中,常见的是json_serializable

示例

第1步

我以他们的例子为参考

  

给出一个带example类的库example.dart   @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步

  

转换为地图

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

第3步

  

反序列化

Person person = Person.from(valueMap)

安装

要安装,只需将其添加到pubspec.yml

dependencies:
  ...
  json_annotation: ^1.2.0

dev_dependencies:
  build_runner: ^0.10.3

然后运行flutter packages get

答案 1 :(得分:0)

这是我不使用json_annotation将JSON转换为对象的方式:

Post和PostViewModel类:

import 'dart:convert';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

class Post {
  final int id;
  final String title;
  final String content;
  final String author;
  final String date;
  final String imgUrl;

  Post(
      {this.id, this.title, this.content, this.author,this.date, this.imgUrl});

  factory Post.fromJson(Map<String, dynamic> json) {
    List<String> contents = json['content']['rendered'].toString().split('"');

    return Post(
        id: json['id'],
        title: json['title']['rendered'],
        content: json['content']['rendered'],
        author: json['_links']['author'][0]['href'],
        date: json['date'],
        imgUrl: contents[33]
    );
  }
}

class PostViewModel {
  static Post post;

  static Future<Post> loadData() async {
    post = new Post();
    try {
      String jsonData = await rootBundle.loadString('assets/data.json');
      post = new Post.fromJson(json.decode(jsonData));
    } catch (e) {
      print(e);
    }
    return post;
  }
}

要演示信息的主页:

import 'package:flutter/material.dart';
import 'package:hello_world/post.dart';

class HomePage extends StatefulWidget {

  @override
  HomePageState createState() => new HomePageState();

}

class HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("Home")),
        body: Material(
            child: Column(children: <Widget>[
              Text(PostViewModel.post.id.toString()),
              Text(PostViewModel.post.title),
              Text(PostViewModel.post.author),
              Text(PostViewModel.post.date),
              Text(PostViewModel.post.imgUrl),
              Text(PostViewModel.post.content)
            ])));
  }
}

图片:

enter image description here

只是注意到我在提供的JSON中找不到imgUrl字段,但我认为它是content[rendered]字段中提供的图片网址,因此使用了它。