我需要从json获取数据,但是
我有一个API,它返回的数据类型为_HttpClientResponse,因为我使用的是httpClient,我使用下面的我需要从json获取数据,但是,json,flutter,dart,Json,Flutter,Dart,我有一个API,它返回的数据类型为_HttpClientResponse,因为我使用的是httpClient,我使用下面的 var reply = await memoryResponse.transform(utf8.decoder).join(); 当我打印结果时 I/颤振(23708):弦 I/颤振(23708):{“结果”: [{“IPAddress”:“192.1.1.1”,“Description”:“Windows 2016 Server”}, {“IPAddress”:“19
var reply = await memoryResponse.transform(utf8.decoder).join();
当我打印结果时
I/颤振(23708):弦
I/颤振(23708):{“结果”:
[{“IPAddress”:“192.1.1.1”,“Description”:“Windows 2016 Server”},
{“IPAddress”:“192.1.1.1”,“说明”:“Windows 2016 Server”},{“IPAddress”:“192.1.1.1”,“说明”:“Windows 2016 Server”}]}
然后用json.decod对其进行解码
var memJasonData=json.decode(reply);
当我打印运行类型时
_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 }]}
但对我来说没什么用
我感谢你的帮助
功能
''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;
} '''
Future\u getMemoryData()异步{
var url='1〕https://10.1.1.1/v3/Json/Query?query';
HttpClient=新的HttpClient();
client.addCredentials(Uri.parse(url),'10.1.1.1',
HttpClientBasicCredentials('user','pass');
client.badCertificateCallback=
((X509证书证书证书,字符串主机,int端口)=>true);
HttpClientRequest memoryRequest=等待客户端.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=等待memoryRequest.close();
var reply=await memoryResponse.transform(utf8.decoder.join();
var memJasonData=json.decode(reply);
//var memToListData=memJasonData['results']作为列表;
List\u getMemoryData1=memJasonData.map((json)=>
Results.fromJson(json)).toList();
设置状态(){
打印(_getMemoryData1);
getMemoryData=_getMemoryData1;
打印(getMemoryData);
});
//for(memToListData中的var v){
//结果memResults=Results(v['iPAddress']、v['description']、v['dNS']、v['sysName']、v['vendor']、v['status']、v['lastBoot']、v['percentMemoryUsed']、v['percentMemoryAvailable']、v['machineType']);
//添加(memResults);
// }
//打印(getMemoryData.length);
//打印(getMemoryData.runtimeType);
//返回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'];
}
下面是这个类
课堂成绩{
字符串地址;
字符串描述;
字符串dNS;
字符串sysName;
字符串供应商;
智力状态;
字符串lastBoot;
整数百分比被使用;
可用内存的整数百分比;
字符串机器类型;
结果(
这是我的地址,
这个.说明,,
这个.dNS,
这个.sysName,
这个供应商,
这个,身份,,
这是最后一只靴子,
这是你的,
这是一个可用的,
这个机器类型,
);
Results.fromJson(映射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'];
}
错误
类型“(动态)=>Results”不是类型“(字符串,动态)=>
“转换”的“映射条目”您可以复制粘贴并运行下面的完整代码
如果您的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,
};
}
你所说的“没有什么对我有用”是什么意思。我没有得到确切的要点和您得到的错误消息。我构建了一个列表来显示json的内容,但该列表有15项“结果实例”结果是我调用它来构建列表的类的名称
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