0
点赞
收藏
分享

微信扫一扫

flutter Json 与map转换


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.}
 

举报

相关推荐

0 条评论