Flutter-json解析

推荐一个json转实体类的在线网站,功能同于android原生的jsonFormate插件

https://javiercbk.github.io/json_to_dart/?tdsourcetag=s_pcqq_aiomsg

 

 

import 'package:flutter/material.dart';
import 'dart:convert';

void main() {
  runApp(new MyJson());
}

class Person {
  String name;
  String age;
  Person child;
  List friend;

  Person({this.name, this.age, this.child, this.friend});

  Person.fromJson(Map json) {
    name = json['name'];
    age = json['age'];
    child = json['child'] != null ? new Person.fromJson(json['child']) : null;
    if (json['friend'] != null) {
      friend = new List();
      json['friend'].forEach((v) {
        friend.add(new Person.fromJson(v));
      });
    }
  }

  Map toJson() {
    final Map data = new Map();
    data['name'] = this.name;
    data['age'] = this.age;
    if (this.child != null) {
      data['child'] = this.child.toJson();
    }
    if (this.friend != null) {
      data['friend'] = this.friend.map((v) => v.toJson()).toList();
    }
    return data;
  }
}





class MyJson extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('json解析'),
            ),
            body: Container(
              padding: EdgeInsets.all(10.0),
              child: Column(
                children: [
                  RaisedButton(
                    onPressed: decode,
                    child: Text("解析"),
                  ),
                ],
              ),
            )));
  }
}

decode() {
  String jsonString = '''
  {"name":"王子","age":"12","child":{"age":"12","name":"王小二"},"friend":[{"age":"2"},{"age":"23"}]}
''';
  // 解析 json 字符串,返回的是 Map 类型
  final jsonMap = json.decode(jsonString);
  print('jsonMap runType is ${jsonMap.runtimeType}');

  Person person = Person.fromJson(jsonMap);
  List ps=person.friend;
  print('person name is ${person.name}, age is ${person.age}, height is ${ps.asMap().length}');

}

你可能感兴趣的:(Flutter)