如何在Flutter中解析PurpleAir JSON?

时间:2019-02-16 02:56:01

标签: json dart flutter

所以我正在尝试从here解析PurpleAir JSON。

使用this documentation

我无法访问我真正想要的数据,例如实时2.5 AQI读取。

这是我的代码,它以字符串形式返回已解析的JSON数据,我所能获得的只是地图版本,有人可以告诉我如何修改此代码以获取其他数据吗?(基本上,我要输入什么内容) jsonResponse括号以获取标记为/v./)的元素

Future<String> sensorTest() async{
  var url = "https://www.purpleair.com/json?show=15130";
  var response =  await http.get(url);//Parses it
   if (response.statusCode == 200){
      var jsonResponse = convert.jsonDecode(response.body);
      var aqi = jsonResponse['mapVersion']; 
      String output = "Map Version: "+aqi;
      return output;
   }
   else{
     return "Something is wrong";
   }    
}

2 个答案:

答案 0 :(得分:0)

我重构代码以使其更具可读性,并且对我有用,print得到了我的帮助:

  

地图版本:0.72

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<String> sensorTest() async {
    const String url = 'https://www.purpleair.com/json?show=15130';
    final http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      final dynamic jsonResponse = jsonDecode(response.body);
      final dynamic aqi = jsonResponse['mapVersion'];
      final String output = 'Map Version: $aqi';
      print(output);
      return output;
    } else
      return 'Something is wrong';
  }

要获得v,您可以这样做:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<String> sensorTest() async {
    const String url = 'https://www.purpleair.com/json?show=15130';
    final http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      final dynamic jsonResponse = jsonDecode(response.body);
      final dynamic aqi = jsonResponse['results'][0]['Stats']['v'];
      final String v = 'V: $aqi';
      print(v);
      return v;
    } else
      return 'Something is wrong';
  }

答案 1 :(得分:0)

此代码应该有效:

mapper.Map(x => x.GroupId).Formula("(select case when exists (select * from INFORMATION_SCHEMA.COLUMNS SYS_COLS_TBL WHERE SYS_COLS_TBL.TABLE_NAME ='Azure' AND SYS_COLS_TBL.COLUMN_NAME = 'GroupId') then this_.GroupId else '' end)");

结果:

Map version: 0.73
v: 10.48
v2: 9.74
v3: 8.68

数据模型:

import 'dart:convert';

import 'json_objects.dart';

import 'package:http/http.dart' as _http;

Future<void> main() async {
  var url = 'https://www.purpleair.com/json?show=15130';
  var response = await _http.get(url);
  if (response.statusCode == 200) {
    var json = jsonDecode(response.body) as Map<String, dynamic>;
    var response1 = Response1.fromJson(json);
    print('Map version: ${response1.mapVersion}');
    for (var result in response1.results) {
      var temp = result.stats.replaceAll('\'', '');
      var json = jsonDecode(temp) as Map<String, dynamic>;
      var stats = Stats.fromJson(json);
      print('v: ${stats.v}');
      print('v2: ${stats.v1}');
      print('v3: ${stats.v3}');
    }
  }
}