【问题标题】:Handling JSON as String in Flutter在 Flutter 中将 JSON 作为字符串处理
【发布时间】:2020-10-27 02:19:13
【问题描述】:

我已尝试获取教师列表:

在提供者老师我有:

Future<void> getTeachers() async {
    final String url = "http://10.0.2.2:8000/teachers/";
    try {
      final response = await http.get(url);
      final extractedData = json.encode(json.decode(response.body));
      final List<Teacher> loadedTeachers = [];

      extractedData.forEach((teacherId, teacherData) {
        loadedTeachers.add(Teacher(
          id: teacherData["uuid"],
          firstname: teacherData["firstname"],
          lastname: teacherData["lastname"],
          location: teacherData["location"],
          imageUrl: "",
          isActive: true,
          isFavorite: false,
        ));
      });
      _coaches = loadedCoaches;

 

      notifyListeners();
    } catch (error) {
      throw error;
    }
  }

但是在对 response.body 进行编码后,它返回一个字符串,因此我不能像 extractedTeachers.forEach 那样遍历它来为每个对象创建一个 Teacher 对象。我该如何处理?

更新: JSON 示例

[
    {
        "uuid": "b1bcfc7b-a847-4069-ba76-a4bf274d95e9",
        "first_name": "John",
        "last_name": "Doe",
        "email": "JD@gmail.com",
        "is_active": true,
        "profile": null
    },
]

【问题讨论】:

  • 这能回答你的问题吗? Flutter: JSON Loop
  • 你能发布一个示例 json。
  • @SagarAcharya 我已经更新了主题。

标签: flutter dart


【解决方案1】:

看看我为你做的例子:

下面是你提供的json:

[
    {
        "uuid": "b1bcfc7b-a847-4069-ba76-a4bf274d95e9",
        "first_name": "John",
        "last_name": "Doe",
        "email": "JD@gmail.com",
        "is_active": true,
        "profile": null
    }
]

json 的模型类:

// To parse this JSON data, do
//
//     final teachers = teachersFromJson(jsonString);

import 'dart:convert';

List<Teachers> teachersFromJson(String str) => List<Teachers>.from(json.decode(str).map((x) => Teachers.fromJson(x)));

String teachersToJson(List<Teachers> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Teachers {
    Teachers({
        this.uuid,
        this.firstName,
        this.lastName,
        this.email,
        this.isActive,
        this.profile,
    });

    String uuid;
    String firstName;
    String lastName;
    String email;
    bool isActive;
    dynamic profile;

    factory Teachers.fromJson(Map<String, dynamic> json) => Teachers(
        uuid: json["uuid"],
        firstName: json["first_name"],
        lastName: json["last_name"],
        email: json["email"],
        isActive: json["is_active"],
        profile: json["profile"],
    );

    Map<String, dynamic> toJson() => {
        "uuid": uuid,
        "first_name": firstName,
        "last_name": lastName,
        "email": email,
        "is_active": isActive,
        "profile": profile,
    };
}

下面是实现:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:json_parsing_example/models.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Index(),
    );
  }
}

class Index extends StatefulWidget {
  @override
  _IndexState createState() => _IndexState();
}



class _IndexState extends State<Index> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Text('sample'),
    );
  }

  Future<String> fetchData() async {
    String data =
        await DefaultAssetBundle.of(context).loadString("json/parse.json");
  // this is using the model
    final teachers = teachersFromJson(data);
    print('This is the list of Strings ${teachers.length}');

/* "uuid": "b1bcfc7b-a847-4069-ba76-a4bf274d95e9",
        "first_name": "John",
        "last_name": "Doe",
        "email": "JD@gmail.com",
        "is_active": true,
        "profile": null */

        // this below using using the map iteration

    List<Teacher> teacherList = List();

    final jsonResult = json.decode(data);
    jsonResult.forEach((element) {
      Teacher teacher = Teacher(
        id: element['uuid'],
        firstname: element['first_name'],
        lastname: element['last_name'],
        email: element['email'],
        isActive: element['is_active'],
        profile: element['profile'],
      );

      teacherList.add(teacher);
    });

    print('This is map iterated list for teacher ${teacherList.length}');

   
    return "Success!";
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }



}





class Teacher {
  final String id;
  final String firstname;
  final String lastname;
  final String email;
  final bool isActive;
  final String profile;

  Teacher(
      {this.id,
      this.firstname,
      this.lastname,
      this.email,
      this.isActive,
      this.profile});
}

我已经使用模型和使用地图迭代两种方式都完成了,只需检查一下,让我知道它是否有效。

【讨论】:

  • 谢谢。我的代码有问题。我将我的模型作为教师和提供者作为教师分开。在教师内部,您可能会猜到我只是返回一个教师对象,但是在提供者教师中,我在那里获取我的数据。我不在我的小部件中编写逻辑。当为获取的数据中的每个项目返回数据时,我将附加到列表 loadedTeacher 并在循环结束时设置 _teachers = loadedTeacher 然后调用 notifyListener() 以将它们显示在我的小部件上。
  • 太好了。所以它现在可以正常工作了,你自己解决了。我的回答有帮助吗?如果不是这样我可以删除它。告诉我。
  • 是的,谢谢。如果有人不能代表更好的答案,我会确认。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-17
  • 2015-06-28
  • 2021-07-21
  • 2013-01-27
  • 1970-01-01
  • 2014-03-07
相关资源
最近更新 更多