Not Getting desired json response in Dart

2020-05-08 08:13发布

问题:

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.

here is the json link

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

Here is the code

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"),
        ),
      ),
    );
  }
}

I only want to get the number 54 from "text" so I use regex

I expected the output will be 54 but instead I get this error

回答1:

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.

Change:

var line = teerModel["text"].replaceAll(new RegExp(r"(\s\n)"), "");

to

var line = teerModel[0]["text"].replaceAll(new RegExp(r"(\s\n)"), "");

Don't forget to call setState so that your widget rebuilds itself.



标签: dart flutter