问题描述
我目前正在构建一个应用程序,以从json API获取数据。
我想从json代码中获取数字54。
I am currently building an app to get a data from a json api.I want to get the number 54 from the json code.
这是json
我尝试在此处制作json api的模型类
I have tried making model class of the json api here
class TeerModel{
String text;
TeerModel(this.text);
TeerModel.fromJson(Map<String, dynamic>parsedJson){
text = parsedJson['text'];
}
}
但是我无法得到结果,所以我删除了
But I can't get the result so i removed it
这是代码
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'models/teer_model.dart';
import 'dart:convert';
class Appss extends StatefulWidget {
@override
_AppssState createState() => _AppssState();
}
class _AppssState extends State<Appss> {
String result = "1S";
void fetchData ()async{
var response1 = await get("http://motyar.info/webscrapemaster/api/?url=http://teertoday.com/&xpath=/html/body/div[5]/div/table/tbody/tr[3]/td[1]#vws");
var teerModel = json.decode(response1.body);
var line = teerModel["text"].replaceAll(new RegExp(r"(\s\n)"), "");
print(line);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Teer result"),),
floatingActionButton: FloatingActionButton(
onPressed: fetchData,
),
body: Center(
child: Text("The result is: $result"),
),
),
);
}
}
我只想从文本中获取数字54 所以我使用正则表达式
I only want to get the number 54 from "text" so I use regex
我希望输出为54,但我却收到此错误
I expected the output will be 54 but instead I get this error
推荐答案
如果您查看json,您会发现它完全被 [...]
包围,这意味着它是一个json数组。 json.decode
会将其转换为Dart List< Map< String,dynamic>>
。看来您想要此数组/列表的第一个/第零个元素。
If you look at your json, you will see that it is entirely surrounded by [...]
, meaning that it is a json array. json.decode
will convert this into a Dart List<Map<String, dynamic>>
. It looks like you want the first / zero'th element of this array/list.
更改:
var line = teerModel["text"].replaceAll(new RegExp(r"(\s\n)"), "");
到
var line = teerModel[0]["text"].replaceAll(new RegExp(r"(\s\n)"), "");
别忘了调用 setState
您的小部件会自行重建。
Don't forget to call setState
so that your widget rebuilds itself.
这篇关于在Dart中未获得所需的json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!