【问题标题】:Issue in JSON to Map formatting in FlutterJSON 中的问题映射到 Flutter 中的格式
【发布时间】:2021-09-01 15:35:46
【问题描述】:

我是 Flutter 的新手,但遇到了一些问题。我正在开发一个简单的 Flutter 应用程序,在该应用程序中,我从 Internet 获取一个 JSON 文件,将其解析为 Map,并显示它。在 JSON 文件中的特定图书对象键 publishedDate 中,该值是另一个名为 $date 的对象,它具有我尝试访问的实际出版日期。

问题是,虽然我可以访问每个对象键及其值,但由于某种原因,当我尝试访问 publishedDate.$date 时,我得到了 null 回来。鉴于我可以访问任何其他对象键及其值这一事实,我认为问题出在书籍模型文件中,它将 JSON 解析为 Map。

我该如何解决这个问题?

这是我认为问题所在的部分。我还要附上一部分 JSON 文件和整个图书模型文件。

class PublishedDate {

  String? $date;

  PublishedDate({this.$date});

  PublishedDate.fromJson(Map<String, dynamic> json) {
    this.$date = json["${$date}"];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["${$date}"] = this.$date;
    return data;
  }
}

整本书模型

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:flutter/services.dart' show rootBundle;

class BookData {
  int? id;
  String? title;
  String? isbn;
  int? pageCount;
  PublishedDate? publishedDate;
  String? thumbnailUrl;
  String? shortDescription;
  String? longDescription;
  String? status;
  List<dynamic>? authors;
  List<dynamic>? categories;

  BookData({this.id, this.title, this.isbn, this.pageCount, this.publishedDate, this.thumbnailUrl, this.shortDescription, this.longDescription, this.status, this.authors, this.categories});

  BookData.fromJson(Map<String, dynamic> json) {
    this.id = json["_id"] == null ? null : json["_id"];
    this.title = json["title"];
    this.isbn = json["isbn"];
    this.pageCount = json["pageCount"];
    this.publishedDate = json["publishedDate"] == null ? null : PublishedDate.fromJson(json["publishedDate"]);
    this.thumbnailUrl = json["thumbnailUrl"];
    this.shortDescription = json["shortDescription"];
    this.longDescription = json["longDescription"];
    this.status = json["status"];
    this.authors = json["authors"] ?? [];
    this.categories = json["categories"] ?? [];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if(this.id != null)
      data["_id"] = this.id;
    data["title"] = this.title;
    data["isbn"] = this.isbn;
    data["pageCount"] = this.pageCount;
    if(this.publishedDate != null)
      data["publishedDate"] = this.publishedDate?.toJson();
    data["thumbnailUrl"] = this.thumbnailUrl;
    data["shortDescription"] = this.shortDescription;
    data["longDescription"] = this.longDescription;
    data["status"] = this.status;
    if(this.authors != null)
      data["authors"] = this.authors;
    if(this.categories != null)
      data["categories"] = this.categories;
    return data;
  }

  static getBooksAll() async{
    var bookURL = "https://raw.githubusercontent.com/a-starck02/book_data/main/bookData_complex.json";
    var response = await http.get(Uri.parse(bookURL));
    var listToPass = jsonDecode(response.body);
    List<BookData> bookData = List<BookData>.from(listToPass.map((i) => BookData.fromJson(i)));
    return bookData;
  }
}

class PublishedDate {

  String? $date;

  PublishedDate({this.$date});

  PublishedDate.fromJson(Map<String, dynamic> json) {
    this.$date = json["${$date}"];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data["${$date}"] = this.$date;
    return data;
  }
}

JSON 文件示例

[
  {
    "_id": 1,
    "title": "Unlocking Android",
    "isbn": "1933988673",
    "pageCount": 416,
    "publishedDate": {
      "$date": "2009-04-01T00:00:00.000-0700"
    },
    "thumbnailUrl": "https://s3.amazonaws.com/AKIAJC5RLADLUMVRPFDQ.book-thumb-images/ableson.jpg",
    "shortDescription": "Unlocking Android: A Developer's Guide provides concise, hands-on instruction for the Android operating system and development tools. This book teaches important architectural concepts in a straightforward writing style and builds on this with practical and useful examples throughout.",
    "longDescription": "Android is an open source mobile phone platform based on the Linux operating system and developed by the Open Handset Alliance, a consortium of over 30 hardware, software and telecom companies that focus on open standards for mobile devices. Led by search giant, Google, Android is designed to deliver a better and more open and cost effective mobile experience.    Unlocking Android: A Developer's Guide provides concise, hands-on instruction for the Android operating system and development tools. This book teaches important architectural concepts in a straightforward writing style and builds on this with practical and useful examples throughout. Based on his mobile development experience and his deep knowledge of the arcane Android technical documentation, the author conveys the know-how you need to develop practical applications that build upon or replace any of Androids features, however small.    Unlocking Android: A Developer's Guide prepares the reader to embrace the platform in easy-to-understand language and builds on this foundation with re-usable Java code examples. It is ideal for corporate and hobbyists alike who have an interest, or a mandate, to deliver software functionality for cell phones.    WHAT'S INSIDE:        * Android's place in the market      * Using the Eclipse environment for Android development      * The Intents - how and why they are used      * Application classes:            o Activity            o Service            o IntentReceiver       * User interface design      * Using the ContentProvider to manage data      * Persisting data with the SQLite database      * Networking examples      * Telephony applications      * Notification methods      * OpenGL, animation & multimedia      * Sample Applications  ",
    "status": "PUBLISH",
    "authors": [
      "W. Frank Ableson",
      "Charlie Collins",
      "Robi Sen"
    ],
    "categories": [
      "Open Source",
      "Mobile"
    ]
  },
  {
    "_id": 2,
    "title": "Android in Action, Second Edition",
    "isbn": "1935182722",
    "pageCount": 592,
    "publishedDate": {
      "$date": "2011-01-14T00:00:00.000-0800"
    },
    "thumbnailUrl": "https://s3.amazonaws.com/AKIAJC5RLADLUMVRPFDQ.book-thumb-images/ableson2.jpg",
    "shortDescription": "Android in Action, Second Edition is a comprehensive tutorial for Android developers. Taking you far beyond \"Hello Android,\" this fast-paced book puts you in the driver's seat as you learn important architectural concepts and implementation strategies. You'll master the SDK, build WebKit apps using HTML 5, and even learn to extend or replace Android's built-in features by building useful and intriguing examples. ",
    "longDescription": "When it comes to mobile apps, Android can do almost anything   and with this book, so can you! Android runs on mobile devices ranging from smart phones to tablets to countless special-purpose gadgets. It's the broadest mobile platform available.    Android in Action, Second Edition is a comprehensive tutorial for Android developers. Taking you far beyond \"Hello Android,\" this fast-paced book puts you in the driver's seat as you learn important architectural concepts and implementation strategies. You'll master the SDK, build WebKit apps using HTML 5, and even learn to extend or replace Android's built-in features by building useful and intriguing examples. ",
    "status": "PUBLISH",
    "authors": [
      "W. Frank Ableson",
      "Robi Sen"
    ],
    "categories": [
      "Java"
    ]
  },
]

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    将 $date 重命名为数据

    class PublishedDate {
      PublishedDate({
        required this.date,
      });
    
      final String date;
    
      factory PublishedDate.fromJson(Map<String, dynamic> json) => PublishedDate(
            date: json["\u0024date"],
          );
    
      Map<String, dynamic> toJson() => {
            "\u0024date": date,
          };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 2018-07-03
      • 2012-09-09
      • 1970-01-01
      相关资源
      最近更新 更多