【问题标题】:Parsing complex json flutter解析复杂的json颤动
【发布时间】:2020-09-28 05:14:49
【问题描述】:

我正在尝试将复杂的 json 文件解析到我的应用程序中 我收到一个错误Exception: type 'String' is not a subtype of type 'int' in type cast。我不明白这是发生在哪里以及如何解决它

代码

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

Future<List<Character>> fetchCharacters(http.Client client) async {
  final response =
  await client.get('http://swapi.dev/api/people/');
  // Use the compute function to run parsePhotos in a separate isolate.
  return compute(parseCharacter, response.body);
}

// A function that converts a response body into a List<Photo>.
List<Character> parseCharacter(String responseBody) {
  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map<Character>((json) => Character.fromJson(json)).toList();
}

class Character {
  final String name;
  final int height;
  final int mass;
  final String hairColor;
  final String skinColor;
  Character({this.name, this.height, this.mass, this.hairColor, this.skinColor});
  factory Character.fromJson(Map<String, dynamic> json) {
    return Character(
      name: json['name'] as String,
      height: json['height'] as int,
      mass: json['mass'] as int,
      hairColor: json['hair_color'] as String,
      skinColor: json['skin_color'] as String,
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Isolate Demo';
    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: FutureBuilder<List<Character>>(
        future: fetchCharacters(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? PhotosList(character: snapshot.data)
              : Center(child: CircularProgressIndicator());
        },
      ),
    );
  }
}

class PhotosList extends StatelessWidget {
  final List<Character> character;
  PhotosList({Key key, this.character}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: character.length,
      itemBuilder: (context, index) {
        return Card(
          elevation: 5,
          margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
          child: Container(
            padding: EdgeInsets.all(15),
            child: ListTile(
              title: Text(
                character[index].name,
                style: TextStyle(fontSize: 18, color: Colors.black),
              ),
              onTap: () {},
            ),
          ),
        );
      },
    );
  }
}

json 文件

    "count": 82,
    "next": "http://swapi.dev/api/people/?page=2",
    "previous": null,
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue",
            "birth_year": "19BBY",
            "gender": "male",
            "homeworld": "http://swapi.dev/api/planets/1/",
            "films": [
                "http://swapi.dev/api/films/1/",
                "http://swapi.dev/api/films/2/",
                "http://swapi.dev/api/films/3/",
                "http://swapi.dev/api/films/6/"
            ],
            "species": [],
            "vehicles": [
                "http://swapi.dev/api/vehicles/14/",
                "http://swapi.dev/api/vehicles/30/"
            ],
            "starships": [
                "http://swapi.dev/api/starships/12/",
                "http://swapi.dev/api/starships/22/"
            ],
            "created": "2014-12-09T13:50:51.644000Z",
            "edited": "2014-12-20T21:17:56.891000Z",
            "url": "http://swapi.dev/api/people/1/"
        } 
   ]
} ```

【问题讨论】:

  • 如错误所述,当您的类模型类型为 String 时,json 返回类型为 int,因此请再次检查并确保一切匹配。
  • 我是 Flutter 的新手,你能告诉我具体在哪里吗?
  • 把你的质量和高度改为字符串
  • return parsed['results'].map&lt;Character&gt;((json) =&gt; Character.fromJson(json)).toList();

标签: json flutter dart


【解决方案1】:

只需删除您在构造函数中添加的as int 并使用parseInt( json['mass'] )parseInt( json['height'] )

parseInt() 是 dart 中的一个函数,用于将 int 类型的数字字符串转换为整数,可用于计算等

也检查一下:https://dev.to/wangonya/how-you-turn-a-string-into-a-number-or-vice-versa-with-dart-392h

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 2021-06-26
    • 2020-08-14
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多