当前位置: 首页 > 知识库问答 >
问题:

我需要从json获取数据,但是

宰宣
2023-03-14

我有一个API,它返回的数据类型为_HttpClientResponse,因为我使用的是httpClient,我使用下面的

 var reply = await memoryResponse.transform(utf8.decoder).join();

当我打印结果i/flatter(23708):字符串i/flatter(23708):{“结果”:[{“IPAddress”:“192.1.1.1”,“说明”:“Windows 2016 Server”},{“IPAddress”:“192.1.1.1”,“说明”:“Windows 2016 Server”},{“IPAddress”:“192.1.1.1”,“说明”:“Windows 2016 Server”}

然后解码它与json.decodvar memJasonData=json.decode(回复);当我打印runType

_InternalLinkedHashMap<String, dynamic>
{results:[{IPAddress": 192.1.1.1, Description: Windows 2016 Server},
{IPAddress: 192.1.1.1", Description : Windows 2016 Server },{ IPAddress : 
192.1.1.1", Description : Windows 2016 Server }]}

我创建了一个类在这里使用,我尝试了

List<Results> _getMemoryData1 = memJasonData.map((json) => 
Results.fromJson(json)).toList();
setState(() {
  print(_getMemoryData1);
  getMemoryData = _getMemoryData1;
  print(getMemoryData);

在将地图转换为列表后,我还尝试了lop

var memToListData = memJasonData['results'] as List; '''

但对我没什么用

我很感激你的帮助

函数“”var getMemoryData=const[];

Future _getMemoryData() async {
  var url ='https://10.1.1.1/v3/Json/Query?query';
  HttpClient client = new HttpClient();
       client.addCredentials(Uri.parse(url), '10.1.1.1',
    HttpClientBasicCredentials('user', 'pass'));
 client.badCertificateCallback =
 ((X509Certificate cert, String host, int port) => true);
 HttpClientRequest memoryRequest = await client.getUrl(Uri.parse(
    '$url=SELECT+TOP+15+IPAddress,+Description,+DNS,+SysName,+Vendor,+Status,+Last Boot,+PercentMemoryUsed,+PercentMemoryAvailable,+MachineType,     +TotalMemory+FROM+Orion.Nodes+ORDER+By+PercentMemoryUsed+DESC'));
  memoryRequest.headers.set('content-type', 'application/json',);

 HttpClientResponse memoryResponse = await memoryRequest.close();

var reply = await memoryResponse.transform(utf8.decoder).join();

var memJasonData = json.decode(reply);

//    var memToListData = memJasonData['results'] as List;


List<Results> _getMemoryData1 = memJasonData.map((json) => 
Results.fromJson(json)).toList();
      setState(() {
        print(_getMemoryData1);
        getMemoryData = _getMemoryData1;
        print(getMemoryData);
      });


//    for (var v in memToListData){
//      Results memResults = Results(v['iPAddress'], v['description'], v['dNS'], v['sysName'], v['vendor'], v['status'], v['lastBoot'], v['percentMemoryUsed'], v['percentMemoryAvailable'], v['machineType']);
//      getMemoryData.add(memResults);
//     }
//    print(getMemoryData.length);
//    print(getMemoryData.runtimeType);

//    return getMemoryData;


 } '''

下等

below is the class   
class Results {
  String iPAddress;
  String description;
  String dNS;
  String sysName;
  String vendor;
  int status;
  String lastBoot;
  int percentMemoryUsed;
  int percentMemoryAvailable;
  String machineType;

Results(
  this.iPAddress,
  this.description,
  this.dNS,
  this.sysName,
  this.vendor,
  this.status,
  this.lastBoot,
  this.percentMemoryUsed,
  this.percentMemoryAvailable,
  this.machineType,
  );

Results.fromJson(Map<String, dynamic> json) :
  iPAddress = json['IPAddress'],
  description = json['Description'],
  dNS = json['DNS'],
  sysName = json['SysName'],
  vendor = json['Vendor'],
  status = json['Status'],
  lastBoot = json['LastBoot'],
  percentMemoryUsed = json['PercentMemoryUsed'],
  percentMemoryAvailable = json['PercentMemoryAvailable'],
  machineType = json['MachineType'];


  }

错误类型(动态)=

共有1个答案

阎星河
2023-03-14

如果json如下所示,您可以复制粘贴并运行下面的完整代码

{"results": [
     {"IPAddress":"192.1.1.1",
     "Description":"Windows 2016 Server",
         "DNS" : "",
         "SysName" :"",
         "Vendor":"",
         "Status":12,
         "LastBoot":"",
         "PercentMemoryUsed":123,
         "PercentMemoryAvailable": 456,
         "MachineType":""
     }, {"IPAddress":"192.1.1.1","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.1",
     "Description":"Windows 2016 Server"}]}

用于解析和打印的代码段

Payload payload = payloadFromJson(jsonString);
print('${payload.results[0].ipAddress}');

相关类

// To parse this JSON data, do
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
    List<Result> results;

    Payload({
        this.results,
    });

    factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        results: List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "results": List<dynamic>.from(results.map((x) => x.toJson())),
    };
}

class Result {
    String ipAddress;
    String description;
    String dns;
    String sysName;
    String vendor;
    int status;
    String lastBoot;
    int percentMemoryUsed;
    int percentMemoryAvailable;
    String machineType;

    Result({
        this.ipAddress,
        this.description,
        this.dns,
        this.sysName,
        this.vendor,
        this.status,
        this.lastBoot,
        this.percentMemoryUsed,
        this.percentMemoryAvailable,
        this.machineType,
    });

    factory Result.fromJson(Map<String, dynamic> json) => Result(
        ipAddress: json["IPAddress"],
        description: json["Description"],
        dns: json["DNS"] == null ? null : json["DNS"],
        sysName: json["SysName"] == null ? null : json["SysName"],
        vendor: json["Vendor"] == null ? null : json["Vendor"],
        status: json["Status"] == null ? null : json["Status"],
        lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
        percentMemoryUsed: json["PercentMemoryUsed"] == null ? null : json["PercentMemoryUsed"],
        percentMemoryAvailable: json["PercentMemoryAvailable"] == null ? null : json["PercentMemoryAvailable"],
        machineType: json["MachineType"] == null ? null : json["MachineType"],
    );

    Map<String, dynamic> toJson() => {
        "IPAddress": ipAddress,
        "Description": description,
        "DNS": dns == null ? null : dns,
        "SysName": sysName == null ? null : sysName,
        "Vendor": vendor == null ? null : vendor,
        "Status": status == null ? null : status,
        "LastBoot": lastBoot == null ? null : lastBoot,
        "PercentMemoryUsed": percentMemoryUsed == null ? null : percentMemoryUsed,
        "PercentMemoryAvailable": percentMemoryAvailable == null ? null : percentMemoryAvailable,
        "MachineType": machineType == null ? null : machineType,
    };
}

完整代码

import 'package:flutter/material.dart';
// To parse this JSON data, do
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  List<Result> results;

  Payload({
    this.results,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        results:
            List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "results": List<dynamic>.from(results.map((x) => x.toJson())),
      };
}

class Result {
  String ipAddress;
  String description;
  String dns;
  String sysName;
  String vendor;
  int status;
  String lastBoot;
  int percentMemoryUsed;
  int percentMemoryAvailable;
  String machineType;

  Result({
    this.ipAddress,
    this.description,
    this.dns,
    this.sysName,
    this.vendor,
    this.status,
    this.lastBoot,
    this.percentMemoryUsed,
    this.percentMemoryAvailable,
    this.machineType,
  });

  factory Result.fromJson(Map<String, dynamic> json) => Result(
        ipAddress: json["IPAddress"],
        description: json["Description"],
        dns: json["DNS"] == null ? null : json["DNS"],
        sysName: json["SysName"] == null ? null : json["SysName"],
        vendor: json["Vendor"] == null ? null : json["Vendor"],
        status: json["Status"] == null ? null : json["Status"],
        lastBoot: json["LastBoot"] == null ? null : json["LastBoot"],
        percentMemoryUsed: json["PercentMemoryUsed"] == null
            ? null
            : json["PercentMemoryUsed"],
        percentMemoryAvailable: json["PercentMemoryAvailable"] == null
            ? null
            : json["PercentMemoryAvailable"],
        machineType: json["MachineType"] == null ? null : json["MachineType"],
      );

  Map<String, dynamic> toJson() => {
        "IPAddress": ipAddress,
        "Description": description,
        "DNS": dns == null ? null : dns,
        "SysName": sysName == null ? null : sysName,
        "Vendor": vendor == null ? null : vendor,
        "Status": status == null ? null : status,
        "LastBoot": lastBoot == null ? null : lastBoot,
        "PercentMemoryUsed":
            percentMemoryUsed == null ? null : percentMemoryUsed,
        "PercentMemoryAvailable":
            percentMemoryAvailable == null ? null : percentMemoryAvailable,
        "MachineType": machineType == null ? null : machineType,
      };
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  String jsonString = '''
   {"results": [
     {"IPAddress":"192.1.1.1",
     "Description":"Windows 2016 Server",
         "DNS" : "",
         "SysName" :"",
         "Vendor":"",
         "Status":12,
         "LastBoot":"",
         "PercentMemoryUsed":123,
         "PercentMemoryAvailable": 456,
         "MachineType":""
     }, {"IPAddress":"192.1.1.2","Description":"Windows 2016 Server"},{"IPAddress":"192.1.1.3",
     "Description":"Windows 2016 Server"}]}
  ''';
  void _incrementCounter() {
    Payload payload = payloadFromJson(jsonString);
    print('${payload.results[0].ipAddress}');
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

输出

I/flutter ( 9422): 192.1.1.1
 类似资料:
  • 当我们不需要整个序列时,而是只想取开头或结尾的几个元素,我们可以用take()或takeLast()。 Take 如果我们只想要一个可观测序列中的前三个元素那将会怎么样,发射它们,然后让Observable完成吗?take()函数用整数N来作为一个参数,从原始的序列中发射前N个元素,然后完成: private void loadList(List<AppInfo> apps) { mRec

  • 问题内容: 我必须从Jmeter中的这个JSON数组中提取所有“唯一”,然后将这些值存储在数组中,以便以后我可以将其用于每个控制器以附加到另一个URL的尾部。 谁能帮我在Jmeter中做到这一点。 您的帮助将不胜感激。谢谢! 问题答案: 最好使用通过JMeter插件提供的JSONPath Extractor (您需要带有Libs Set的Extras)。 因此,对您的数据遵循JSONPath表达式

  • 我有一个wordpress安装,我在其中安装了codeigniter。一切顺利,我也进入了数据库。现在我为wordpress安装了一个插件:WooCommerce。使用这个插件,您可以在数据库中存储产品和productdata。现在我需要在codeigniter应用程序中访问来自woocommerce产品的数据。 Woocommerce是这样存储其产品的: 所有产品都进入一个名为:wp_posts

  • 问题内容: 这是我从foursquare获得的JSON的一部分。 JSON格式 我需要获取最后的提示 文本 ,编写它的 用户 以及他编写/发布它的 日期 。 用户 :达米尔·P。 日期 :1314115358 文字 :健身中心 我尝试使用 JQuery ,这可以获取非数组值: 但这不适用于数组。 结果 :未捕获的TypeError:无法读取未定义的属性“文本”。 我也尝试了 $ .each ,但没

  • 我正在努力在Python中做一个实时货币转换器。我已经成功地将URL所需的所有数据提取到Python中。但是,我现在尝试在URL中调用特定字符串。这是我当前的代码: 如您所见,我已经打印了它获取的所有数据,但它现在正在从中打印特定的字符串。 我的问题是,如何从URL解析特定字符串?我听说过json.load,这是我应该使用的东西吗?

  • 问题内容: 我正在获取一个文本文件并填充一个arraylist。为了测试文件,我在继续之前将其打印出来。我只能从文件中看到内存地址,而不能看到实际信息。有什么简单的东西,也许很明显我想念吗? 测试员 问题答案: 有什么简单的东西,也许很明显我想念吗? 是的- 你没有覆盖的,所以你得到的默认实现: Object类的toString方法返回一个字符串,该字符串包括该对象是其实例的类的名称,符号字符“