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.}
相关文章
- java项目添加log4j打印日志+转换系统时间
- )C# Enum,Int,String的互相转换 枚举转换
- Visual Studio Code(VS code)你们都在用吗?或许你们需要看一下这篇博文 Asp.Net Core + SignalR 实现实时通信 Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty
- DataTable和DataRow利用反射直接转换为Model对象的扩展方法类
- Java版Word开发工具Aspose.Words基础转换指南:将Word文档和图像转换为PDF
- 【算法】【递归与动态规划模块】字符串之间转换的最小代价
- Google Earth Engine(GEE)——Error: Projection: The CRS of a map projection could not be parsed.(坐标转换错)
- JSON数组形式字符串转换为Map数组(转为其他的Bean的话,请参考自行变形)
- JSON字符串转换为Map
- 【Java】+map对象转换为json格式对象+2个map对象合并
- 文本结构转换为菜单代码、权限、创建文件结构
- zic2xpm - 将 ZIICS 象棋片段 (chess pieces) 转换为 XBoard (XPM/XIM) 片段的工具。
- 字符转换为16进制字符串以及转换回来的方法
- SQL Server 取日期时间格式 日期与字符串之间的转换
- 前缀,中缀,后缀表达式简介及转换 -- C# 简化小例
- leetcode 538. Convert BST to Greater Tree 把二叉搜索树转换为累加树(简单)