如何使用颤振访问 JSON 对象?

Posted

技术标签:

【中文标题】如何使用颤振访问 JSON 对象?【英文标题】:How Can I access JSON Object using flutter? 【发布时间】:2020-05-09 09:31:48 【问题描述】:

如何访问我的 JSON 对象?

获取Employee Title = null如何直接使用对象?

像这样获取正确的输出Text('Employee Title = $list[0].title') 或直接使用模型对象的任何其他方式?

正确的方法是什么?

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';


class EmployeeModel 
  int userId;
  int id;
  String title;
  String body;

  EmployeeModel(this.userId, this.id, this.title, this.body);

  EmployeeModel.fromJson(Map<String, dynamic> json) 
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    body = json['body'];
  

class EmployeePage extends StatefulWidget 
  @override
  State<StatefulWidget> createState() 
    // TODO: implement createState
    return EmployeePageState();
  


class EmployeePageState extends State<EmployeePage> 
  EmployeeModel model = EmployeeModel();
  List<EmployeeModel> list = List();
  var isLoading = false;

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text('Employee Title = $model.title'),
        ),
        body: isLoading
            ? Center(
          child: CircularProgressIndicator(),
        ):Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[

                ])));
  


  @override
  void initState() 
    super.initState();
    getEmployee(2);
  

  getEmployee(int id) async 
    setState(() 
      isLoading = true;
    );
    final response =
        await http.get("https://jsonplaceholder.typicode.com/posts?userId=$id");
    if (response.statusCode == 200) 
      list = (json.decode(response.body) as List)
          .map((data) => new EmployeeModel.fromJson(data))
          .toList();
      setState(() 
        isLoading = false;
      );
    
  

我的代码运行良好,但我想知道这是正确的方法吗? 这边Text('Employee Title = $list[0].title') 或者如果我想直接使用对象是什么方法?

我的代码运行良好,但我想知道这是正确的方法吗? 这样 Text('员工头衔 = $list[0].title') 或者如果我想直接使用对象是什么方法?

【问题讨论】:

【参考方案1】:

您从未从 json 初始化模型,因此模型的所有属性都为空。试试这样的:

    if (response.statusCode == 200) 
      final employees = json.decode(response.body);
      list = (employees as List)
          .map((data) => new EmployeeModel.fromJson(data))
          .toList();
      setState(() 
        model = new EmployeeModel.fromJson(employees[0]);
        isLoading = false;
      );
    

【讨论】:

【参考方案2】:

我有 2 个模型类:

class EmployeeList 
  final List<Employee> employees;

  EmplyeeList(
    this.employees,
);

  factory EmployeeList.fromJson(List<dynamic> parsedJson) 

    List<Employee> employees = new List<Employee>();
    employees = parsedJson.map((i)=>Employee.fromJson(i)).toList();

    return new EmployeeList(
      employees: employees
    );
  


class Employee
  final String id;
  final String title;
  final String body;
  final String userId;


  Employee(
  String userId;
  String id;
  String title;
  String body;

) ;

  factory Employee.fromJson(Map<String, dynamic> json)
    return new Employee(
      id: json['id'],
      userId:[userId]
      title: json['title'],
      body: json['body'],
    );
  


也许也可以考虑使用 FutureBuilder...来自 Flutter 文档:FutureBuilder

【讨论】:

【参考方案3】:

试试这个,

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

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


class EmployeePage extends StatefulWidget 
  @override
  State<StatefulWidget> createState() => EmployeePageState();


class EmployeePageState extends State<EmployeePage> 
  Future<List<EmployeeModel>> _employeeList;

  @override
  void initState() 
    _employeeList = _getEmployee(2);
    super.initState();
  

  Future<List<EmployeeModel>> _getEmployee(int id) async 
    final response = await http.get(
      "https://jsonplaceholder.typicode.com/posts?userId=$id",
    );
    if (response.statusCode == 200) 
      final jsonBody = json.decode(response.body) as List;
      return jsonBody.map((data) => new EmployeeModel.fromJson(data)).toList();
     else
      throw Exception("Unable to get Employee list");
  

  @override
  Widget build(BuildContext context) 
    return FutureBuilder<List<EmployeeModel>>(
      future: _employeeList,
      builder: (context, snapshot) 
        print(snapshot);
        if (snapshot.hasData)
          return _buildBody(snapshot.data);
        else if (snapshot.hasError)
          return _buildErrorPage(snapshot.error);
        else
          return _buildLoadingPage();
      ,
    );
  

  Widget _buildBody(List<EmployeeModel> employeeList) => Scaffold(
        appBar: AppBar(
          title: Text('Employee Title = $employeeList[0].title'),
        ),
        body: ListView.builder(
          itemCount: employeeList.length,
          itemBuilder: (context, index) 
            return ListTile(
              title: Text(employeeList[index].title),
            );
          ,
        ),
      );

  Widget _buildErrorPage(error) => Material(
        child: Center(
          child: Text("ERROR: $error"),
        ),
      );

  Widget _buildLoadingPage() => Material(
        child: Center(
          child: CircularProgressIndicator(),
        ),
      );


class EmployeeModel 
  int userId;
  int id;
  String title;
  String body;

  EmployeeModel(this.userId, this.id, this.title, this.body);

  EmployeeModel.fromJson(Map<String, dynamic> json) 
    userId = json['userId'];
    id = json['id'];
    title = json['title'];
    body = json['body'];
  


【讨论】:

以上是关于如何使用颤振访问 JSON 对象?的主要内容,如果未能解决你的问题,请参考以下文章

如何在颤振中解析json

如何在颤振本地化中读取嵌套的 json?

如何在颤振中使用 json API 在谷歌地图中添加标记?

如何在颤振中创建 JSON 对象?

在颤振单元测试中访问 rootBundle

如何使用 SQFLite 或 Moor 库将 JSON 数据存储到颤振中的数据库表中