Flutter JSON序列化

1、使用model和不使用model

import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
void main() {
  runApp(new MyApp());
}

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

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

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
class User {
  final String origin;

  User(this.origin);

  User.fromJson(Map<String, dynamic> json)
      : origin = json['origin'];

  Map<String, dynamic> toJson() =>
      {
        'origin': origin,
      };
}


class _MyHomePageState extends State<MyHomePage> {
  var _ipAddress = 'Unknown';

  _getIPAddress() async {
    var url = 'https://httpbin.org/ip';
    var httpClient = new HttpClient();

    String result;
    try {
      var request = await httpClient.getUrl(Uri.parse(url));
      var response = await request.close();
      if (response.statusCode == HttpStatus.OK) {
        var json = await response.transform(Utf8Decoder()).join();

        Map userMap = jsonDecode(json);
        var user = new User.fromJson(userMap);
        print('Howdy, ${user.origin}!');
//        Map<String, dynamic> user = jsonDecode(json);
//        print(' ${user['origin']}');

//        var data = JSON.decode(json);
//        result = data['origin'];
      } else {
        result =
        'Error getting IP address:\nHttp status ${response.statusCode}';
      }
    } catch (exception) {
      result = 'Failed getting IP address';
    }

    // If the widget was removed from the tree while the message was in flight,
    // we want to discard the reply rather than calling setState to update our
    // non-existent appearance.
    if (!mounted) return;

    setState(() {
      _ipAddress = result;
    });
  }
  

  @override
  Widget build(BuildContext context) {
    var spacer = new SizedBox(height: 32.0);

    return new Scaffold(
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('Your current IP address is:'),
            new Text('$_ipAddress.'),
            spacer,
            new RaisedButton(
              onPressed: _getIPAddress,
              child: new Text('Get IP address'),
            ),
          ],
        ),
      ),
    );
  }
}
{
  Map<String, dynamic> user = jsonDecode(json);
  print(' ${user['origin']}');
}
{
  Map userMap = jsonDecode(json);
  var user = new User.fromJson(userMap);
  print('Howdy, ${user.origin}!');
}

2、使用json_serializable

添加依赖

dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^2.0.0
dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^1.0.0
  json_serializable: ^2.0.0

创建model

import 'package:json_annotation/json_annotation.dart';
class User {
  User(this.origin);
  String origin;
}

添加注解(part后面是类名称/添加part会报红)

part 'User.g.dart';

@JsonSerializable()

运行命令

flutter packages pub run build_runner build一次性的生成文件

flutter packages pub run build_runner watch持续性的生成文件

添加fromJson和toJson

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);

    原文作者:Sam
    原文地址: https://zhuanlan.zhihu.com/p/58699975
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞