我有一個我打算在我的應用程式中呈現的 JSON 回應。但是,資料的呈現方式非常不尋常,我無法想到,這讓我想到了我做錯了什么或我需要做什么才能以正確的格式獲取資料。JSON 回應、模型和提供程式類以及小部件都在下面:

正如您在上面的片段中看到的,我已經標記了[在開頭和]結尾處渲染的符號。此外,逗號,(也被標記)出現在每個句號的末尾。我對造成這種情況的原因有點一無所知,但后來注意到 的值paraGraph完全以其在串列中的方式呈現。就像[]開頭和結尾的 以及,which 是分隔串列中每個值的基本符號。這些不應該出現。
JSON 回應:
[
{
"_id": "61ed10bc5d383244bbb89d45",
"paraGraph": [
"Homeopathy, the longest established alternative medicine to come out of Europe, was created in 1796 by Samuel Hahnemann.",
"Hahnemann rejected the mainstream medicine of the late 18th century as irrational and inadvisable because it was largely ineffective and often harmful.",
"He advocated the use of single drugs at lower doses and promoted an immaterial, vitalistic view of how living organisms function.",
"The term homeopathy was coined by Hahnemann and first appeared in print in 1807.",
"He also coined the expression allopathic medicine, which was used to pejoratively refer to traditional Western medicine.",
"Hahnemann began to test what effects various substances may produce in humans, a procedure later called homeopathic proving.",
"These tests required subjects to test the effects of ingesting substances by recording all their symptoms as well as the ancillary conditions under which they appeared.",
"He published a collection of provings in 1805, and a second collection of 65 preparations appeared in his book, Materia Medica Pura (1810).",
"As Hahnemann believed that large doses of drugs that caused similar symptoms would only aggravate illness, he advocated for extreme dilutions.",
"A technique was devised for making dilutions that Hahnemann claimed would preserve the substance's therapeutic properties while removing its harmful effects.",
"Hahnemann believed that this process enhanced the spirit-like medicinal powers of the crude substances.",
"He gathered and published an overview of his new medical system in his book, The Organon of the Healing Art (1810), with a sixth edition published in 1921 that homeopaths still use today.",
"Homeopathy achieved its greatest popularity in the 19th century.",
"It was introduced to the United States in 1825 with the first homeopathic school opening in 1835.",
"Throughout the 19th century, dozens of homeopathic institutions appeared in Europe and the United States.",
"During this period, homeopathy was able to appear relatively successful, as other forms of treatment could be harmful and ineffective.",
"By the end of the century the practice began to wane, with the last exclusively homeopathic medical school in the US closing in 1920.",
"In the 1970s, homeopathy made a significant comeback, with sales of some homeopathic products increasing tenfold.",
"The trend corresponded with the rise of the New Age movement, and may be in part due to an irrational preference for natural products, and the longer consultation times homeopathic practitioners provided."
]
}
]
模型類
import 'dart:convert';
List<History> userFromJson(String str) => List<History>.from(json.decode(str).map((x) => History.fromJson(x)));
String userToJson(List<History> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class History {
String? id;
List<String>? paraGraph;
History({this.id, this.paraGraph});
History.fromJson(Map<String, dynamic> json) {
this.id = json["_id"];
this.paraGraph = json["paraGraph"]==null ? null : List<String>.from(json["paraGraph"]);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["_id"] = this.id;
if(this.paraGraph != null)
data["paraGraph"] = this.paraGraph;
return data;
}
}
提供者類(進行 API 呼叫的類)
class HistoryProvider with ChangeNotifier {
List<dynamic> _data = [];
List<dynamic> get data {
return[..._data];
}
Future<void> getData() async {
final url = Uri.http('192.168.0.8:3008', '/history');
final response = await http.get(url);
List<History> history = userFromJson(response.body);
final extractedData = json.decode(response.body);
print('response $extractedData');
_data = history;
print(_data);
}
}
小部件:
class HomeScreen extends StatefulWidget {
HomeScreenState createState() => HomeScreenState();
}
class HomeScreenState extends State<HomeScreen> {
var _loading = true;
@override
void didChangeDependencies() {
Provider.of<HistoryProvider>(context, listen: false).getData().then((_) {
setState(() {
_loading = false;
});
});
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
var history = Provider.of<HistoryProvider>(context).data;
// TODO: implement build
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
title: const Text('Doctor App'),
),
body: _loading ? Center(
child: CircularProgressIndicator(),
) : ListView.builder( //This is where I render the JSON response(paraGraph)
itemBuilder: (context, index) => Text(
history[index].paraGraph.toString()
),
itemCount: history.length
)
);
}
}
這是第一個列印陳述句輸出的內容:
response [
{_id: 61ed10bc5d383244bbb89d45, paraGraph: [Homeopathy, the longest established alternative medicine to come out of Europe,
was created in 1796 by Samuel Hahnemann., Hahnemann rejected the mainstream medicine of the late 18th century as irrational and
inadvisable because it was largely ineffective and often harmful.,
He advocated the use of single drugs at lower doses and promoted an immaterial, vitalistic view of how living organisms function.,
The term homeopathy was coined by Hahnemann and first appeared in print in 1807.,
He also coined the expression allopathic medicine, which was used to pejoratively refer to traditional Western medicine.,
Hahnemann began to test what effects various substances may produce in humans, a procedure later called homeopathic proving.,
These tests required subjects to test the effects of ingesting substances by recording all their symptoms as well as the ancillary conditions under which they appeared.,
He published a collection of provings in 1805, and a second col
這是第二次列印的輸出:
I/flutter (12016): [Instance of 'History']
uj5u.com熱心網友回復:
這是一個奇怪的json。但是你可以像這樣格式化它。
class _HomeScreenState extends State<HomeScreen> {
List<String> paraGraph = [
"Homeopathy, the longest established alternative medicine to come out of Europe, was created in 1796 by Samuel Hahnemann.",
"Hahnemann rejected the mainstream medicine of the late 18th century as irrational and inadvisable because it was largely ineffective and often harmful.",
"He advocated the use of single drugs at lower doses and promoted an immaterial, vitalistic view of how living organisms function.",
"The term homeopathy was coined by Hahnemann and first appeared in print in 1807.",
"He also coined the expression allopathic medicine, which was used to pejoratively refer to traditional Western medicine.",
"Hahnemann began to test what effects various substances may produce in humans, a procedure later called homeopathic proving.",
"These tests required subjects to test the effects of ingesting substances by recording all their symptoms as well as the ancillary conditions under which they appeared.",
"He published a collection of provings in 1805, and a second collection of 65 preparations appeared in his book, Materia Medica Pura (1810).",
"As Hahnemann believed that large doses of drugs that caused similar symptoms would only aggravate illness, he advocated for extreme dilutions.",
"A technique was devised for making dilutions that Hahnemann claimed would preserve the substance's therapeutic properties while removing its harmful effects.",
"Hahnemann believed that this process enhanced the spirit-like medicinal powers of the crude substances.",
"He gathered and published an overview of his new medical system in his book, The Organon of the Healing Art (1810), with a sixth edition published in 1921 that homeopaths still use today.",
"Homeopathy achieved its greatest popularity in the 19th century.",
"It was introduced to the United States in 1825 with the first homeopathic school opening in 1835.",
"Throughout the 19th century, dozens of homeopathic institutions appeared in Europe and the United States.",
"During this period, homeopathy was able to appear relatively successful, as other forms of treatment could be harmful and ineffective.",
"By the end of the century the practice began to wane, with the last exclusively homeopathic medical school in the US closing in 1920.",
"In the 1970s, homeopathy made a significant comeback, with sales of some homeopathic products increasing tenfold.",
"The trend corresponded with the rise of the New Age movement, and may be in part due to an irrational preference for natural products, and the longer consultation times homeopathic practitioners provided."
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
title: const Text('Doctor App'),
),
body: SingleChildScrollView(
child: Column(
children: [for (String i in paraGraph) Text(i)],
),
),
);
}
}
uj5u.com熱心網友回復:
您只需要更新序列化paragraph屬性的方式:
History.fromJson(Map<String, dynamic> json) {
this.id = json["_id"];
this.paraGraph = (json['paraGraph'] as List).map((e) => e as String).toList() ?? []; //<-- update this
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/420293.html
標籤:
上一篇:錯誤:需要一個“扇區?”型別的值,但得到一個“_JsonMap”型別的值
下一篇:在顫振中初始化未來?
