我有一个API,该API返回_HttpClientResponse的数据类型,原因是我使用的是httpClient,我使用以下代码将结果解码为字符串
var reply = await memoryResponse.transform(utf8.decoder).join();
当我打印结果时 I / flutter(23708):字符串 I / flutter(23708):{“结果”: [{“ IPAddress”:“ 192.1.1.1”,“ Description”:“ Windows 2016 Server”}, {“ IPAddress”:“ 192.1.1.1”,“说明”:“ Windows 2016 Server”},{“ IPAddress”:“ 192.1.1.1”,“ Description”:“ Windows 2016 Server”}]}
然后使用json.decod对其进行解码 var memJasonData = json.decode(reply); 当我打印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);
在将地图转换为列表后,我也尝试过砍
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'];
}
错误 类型'(动态)=>结果'不是类型'(字符串,动态)=>的子类型 “转换”的MapEntry”
答案 0 :(得分:0)
您可以复制粘贴并在下面运行完整代码
如果您的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