zl程序教程

您现在的位置是:首页 >  其他

当前栏目

flutter Json 与map转换

2023-09-27 14:27:38 时间
import 'dart:convert';

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

class HttpDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("http_demo"),
      ),
      body: HttpDemoHome(),
    );
  }
}

class HttpDemoHome extends StatefulWidget {
  @override
  _HttpDemoHomeState createState() => _HttpDemoHomeState();
}

class _HttpDemoHomeState extends State<HttpDemoHome> {
  @override
  void initState() {
    super.initState();
    //requst network
    // fetchPost();
    final post = {"title": "Hello", "description": "nice to meet you."};
    print(post['title']);
    print(post['description']);
    //map to json
    final postJson = json.encode(post);
    print(postJson);
    //json to map
    final postJsonConverted = json.decode(postJson);
    print(postJsonConverted['title']);
    print(postJsonConverted is Map);
    //map to model
    final postModel = Post.fromJson(postJsonConverted);
    print("title:${postModel.title}");
    print("description:${postModel.description}");
    //model print
    print("description:${postModel.tojson()}");
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  void fetchPost() async {
    var url = Uri.parse('https://resources.ninghao.net/demo/posts.json');
    final response = await http.get(url);
    print(response.statusCode);
    print(response.body);
  }
}

class Post {
  final String title;
  final String description;

  Post(this.title, this.description);

  Post.fromJson(Map json)
      : title = json['title'],
        description = json['description'];

  Map tojson() => {'title': title, 'description': description};
}

输出

I/flutter (27104): Hello
I/flutter (27104): nice to meet you.
I/flutter (27104): {"title":"Hello","description":"nice to meet you."}
I/flutter (27104): Hello
I/flutter (27104): true
I/flutter (27104): title:Hello
I/flutter (27104): description:nice to meet you.
I/flutter (27104): description:{title: Hello, description: nice to meet you.}