【问题标题】:JSON Array to JSON ObjectJSON 数组到 JSON 对象
【发布时间】:2020-03-31 00:12:09
【问题描述】:

我正在使用获取 JSON 数组并将其推送到由列表视图读取的 JSON 对象的 HTTP 请求。我很难将 JSON 数组强制转换为 JSON 对象,因此我目前通过json.decode(response.body)[0] 调用每个对象一次。如何将 JSON 数组转换为 JSON 对象并让列表视图读取整个 JSON 对象?

import 'dart:async';
import 'dart:convert';

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

Future<Post> fetchPost() async {
  final url = <my_url>;
  final response =
      await http.get(url);

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON.
    print(json.decode(response.body));
    // TODO: Identify a way to convert JSON Array to JSON Object
    return Post.fromJson(json.decode(response.body)[0]);
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {
  final String title;

  Post({this.title});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      title: json['title']
    );
  }
}

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
Future<Post> post;

  @override
  void initState() {
    super.initState();
    post = fetchPost();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

  • 有没有报错?
  • 可以显示json结果吗?
  • 你能发布你的json响应吗?
  • JSON 是 [{'id': 1, 'title': 'A'}, {'id': 2, 'title': 'B'}。当我删除响应正文上的索引[0] 时,该对象不是Map&lt;String, dynamic&gt;。我想继续删除索引并将整个数组放入一个对象中

标签: json http flutter dart


【解决方案1】:

试试这个,

Future<List<Post>> fetchPost() async {
  final url = <my_url>;
  final response =
  await http.get(url);

  if (response.statusCode == 200) {
  // If the call to the server was successful, parse the JSON.
  print(json.decode(response.body));
  List<dynamic> responseList =  json.decode(response.body);
  // TODO: Identify a way to convert JSON Array to JSON Object
  List<Post> tempList = [];
  responseList.forEach((f) {
  tempList.add(Post.fromJson(f));
  });
  return tempList;
  } else {
  // If that call was not successful, throw an error.
  throw Exception('Failed to load post');
  }
}

class Post {
  final int id;
  final String title;

  Post({this.id, this.title});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(id: json['id'], title: json['title']);
  }
}

class _Frag_CommitteeState extends State<Frag_Committee> {
  Future<List<Post>> post;

  @override
  void initState() {
    super.initState();
    post = fetchPost();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fetch Data Example'),
      ),
      body: Center(
        child: FutureBuilder<List<Post>>(
          future: post,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                return Text(snapshot.data[index].title);
              });
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }

            // By default, show a loading spinner.
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
} 

【讨论】:

  • 谢谢。这没有按原样工作,但我能够破解足够多的代码来让它工作
猜你喜欢
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 2011-01-10
  • 2021-07-31
  • 1970-01-01
  • 2015-02-22
  • 2016-05-08
相关资源
最近更新 更多