Json
Map<String, dynamic> headerJson = json.decode(jsonstring);
Header h = Header.fromJson(headerJson);
class Header {
String url;
String from;
String to;
Header({required this.url, this.from = '', this.to = ''});
Map<String, dynamic> toJson() => {'url': url, 'from': from, 'to': to};
String toJsonString() => {'url': url, 'from': from, 'to': to}.toString();
factory Header.fromJson(Map<String, dynamic> json) {
return Header(
url: json['Url'],
from: json['From'],
to: json['To'],
);
}
}
import 'package:flutter/material.dart';
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
Map<String, dynamic> toJson() => {
'name': name,
'email': email,
};
}
解码逻辑的责任现在转移到了模型内部。通过这个新方法,你可以很容易地解码获得一个 user 实例。
content_copy
Map userMap = jsonDecode(jsonString);
var user = User.fromJson(userMap);
print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');
要对 user 实例进行编码,将 User 对象传到 jsonEncode() 函数中。你不需要调用 toJson() 方法,因为 jsonEncode() 已经帮你做了这件事。
content_copy
String json = jsonEncode(user);