在这篇文章中,我们将向您展示如何在 和 Dart 中将映射、简单数组列表或对象列表转换为 JSON 字符串。 您可能需要将数组列表或映射转换为 JSON 字符串以保存为字符串或作为应用程序上的字符串发送到服务器。
dart::
import 'dart:convert';
您需要这个库来实现 JSON 函数。
如何将map转换为 JSON 字符串:
var ages = {"John":26, "Krishna": 34, "Rahul":67, "Maichel": 33};
String jsonstringmap = json.encode(ages);
print(jsonstringmap);
//output: {"John":26,"Krishna":34,"Rahul":67,"Maichel":33}
如何将数组转换为 JSON 字符串:
List names = ["John", "Krisna", "Rahul", "Maichel"];
String jsonstring = json.encode(names);
print(jsonstring);
//output: ["John","Krisna","Rahul","Maichel"]
将对象数组列表转换为 JSON 字符串:
class Student{
String rollno, name, age;
List marks;
Student({
required this.rollno,
required this.name,
required this.age,
required this.marks
});
}
List students = [
Student(name: "John", rollno: "12", age: "26", marks: [23, 45, 35]),
Student(name: "Krishna", rollno: "12", age: "26", marks: [23, 45, 35]),
Student(name: "Rahul", rollno: "12", age: "26", marks: [23, 45, 35])
];
var studentsmap = students.map((e){
return {
"name": e.name,
"rollno": e.rollno,
"age": e.age,
"marks": e.marks
};
}).toList(); //convert to map
String stringstudents = json.encode(studentsmap);
print(stringstudents);
这段代码的输出:
/*--- output ----
[{
"name": "John",
"rollno": "12",
"age": "26",
"marks": [23, 45, 35]
}, {
"name": "Krishna",
"rollno": "12",
"age": "26",
"marks": [23, 45, 35]
}, {
"name": "Rahul",
"rollno": "12",
"age": "26",
"marks": [23, 45, 35]
}]
*/
或者,
class Student{
String rollno, name, age;
List marks;
Student({
required this.rollno,
required this.name,
required this.age,
required this.marks
});
Map toMap() {
return {
'name': this.name,
'rollno': this.rollno,
'age': this.age,
'marks': this.marks,
};
}
static dynamic getListMap(List items) {
if (items == null) {
return null;
}
List<Map> list = [];
items.forEach((element) {
list.add(element.toMap());
});
return list;
}
}
List students = [
Student(name: "John", rollno: "12", age: "26", marks: [23, 45, 35]),
Student(name: "Krishna", rollno: "12", age: "26", marks: [23, 45, 35]),
Student(name: "Rahul", rollno: "12", age: "26", marks: [23, 45, 35])
];
var studentsmap1 = Student.getListMap(students);
//convert to map
String stringstudents1 = json.encode(studentsmap);
print(stringstudents1);
与上面的输出相同。
这样,您就可以在 和 Dart 中将 、 of 、Map 转换为 JSON 字符串
———END———
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,永久会员只需109元,全站资源免费下载 点击查看详情
站 长 微 信: nanadh666
声明:1、本内容转载于网络,版权归原作者所有!2、本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。3、本内容若侵犯到你的版权利益,请联系我们,会尽快给予删除处理!