扑扑JSON解析映射

时间:2019-06-26 10:32:26

标签: flutter dart

我从后端得到响应:

   {"measurements": {
            "pm10": {
              "name": "pm10",
              "value": 20.8647,
              "unit": "µg/m³"
            },
             "pm25": {
              "name": "pm10",
              "value": 20.8647,
              "unit": "µg/m³"
            },
             "o2": {
              "name": "pm10",
              "value": 20.8647,
              "unit": "µg/m³"
            }

        },
   "station": {
        "city": "{cityName}",
        "name": "{locationName}",
        "latitude": "54.353336",
        "longitude": "18.635283"
    }
    }

这是我现在得到的:

class Pollutions {

    Pollutions.fromJsonMap(Map<String, dynamic> map):
                measurements = Measurements.fromJsonMap(map["measurements"]),
                station = Station.fromJson(map["station"]);

  Map<String, Pollution> measurements;
  Station station;

    Map<String, dynamic> toJson() {
        final data = Map<String, dynamic>();
        data['measurements'] = measurements == null ? null : measurements.jsonDecode(measurements);
        data['station'] = station == null ? null : station.toJson();
        return data;
    }
}

在度量中,我可以获得其他值,但对它们的名称一无所知,它可能是o2,o3,不仅是pm10等。我可以解析此度量以映射键值,其中键将是pm10 ,类似的东西:地图? 地图的Pollutions.fromJsonMaptoJson方法应该如何?

4 个答案:

答案 0 :(得分:0)

您可以使用Dart的JSON功能将字符串解析为JSON对象(在这种情况下为Map的实例),然后遍历键:

final Map<String, Map<String, dynamic>> measurements = jsonDecode(string);

for (MapEntry<String, Map<String, dynamic>> entry in measurements.entries) {
  print(entry.key); // e.g. pm20
  print(entry.value['name']); // e.g. also pm20, but this is the "name" value from your JSON string
  print(entry.value['value']); // e.g. 20.8647
  ...
}

答案 1 :(得分:0)

您可以使用var width = 500, height = 100; var svg = d3.select("svg"); var xScale = d3.scaleLinear().domain([0, 10]).range([10, width - 10]); var xAxis = svg.append("g") .attr("class", "x-axis-right") .attr("transform", `translate(0, ${height - 30})`) .style("fill", "blue") .style("stroke", "none") var xAxisCall = d3.axisBottom(xScale); xAxis.call(xAxisCall); var pathString = xAxis.select("path").attr("d"); console.log(pathString)

中的开箱即用解码器来完成此操作
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="100"></svg>

答案 2 :(得分:0)

此代码应该有效:

import 'dart:convert';

import 'json_objects.dart';

main(List<String> args) {
  var json = jsonDecode(body) as Map<String, dynamic>;
  var pollutions = Pollutions.fromJson(json);
  var measurements = pollutions.measurements;
  for (var key in measurements.keys) {
    var measurement = measurements[key];
    print('$key: ${measurement.unit}');
  }
}

var body = '''
{
  "measurements": {
    "pm10": {
      "name": "pm10",
      "value": 20.8647,
      "unit": "µg/m³"
    },
    "pm25": {
      "name": "pm10",
      "value": 20.8647,
      "unit": "µg/m³"
    },
    "o2": {
      "name": "pm10",
      "value": 20.8647,
      "unit": "µg/m³"
    }
  },
  "station": {
    "city": "{cityName}",
    "name": "{locationName}",
    "latitude": "54.353336",
    "longitude": "18.635283"
  }
}
''';

结果:

pm10: µg/m³
pm25: µg/m³
o2: µg/m³

JSON数据模型:

class Measurement {
  final String name;
  final String unit;
  final double value;

  Measurement({this.name, this.unit, this.value});

  factory Measurement.fromJson(Map<String, dynamic> json) {
    return Measurement(
      name: json['name'] as String,
      unit: json['unit'] as String,
      value: _toDouble(json['value']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'unit': unit,
      'value': value,
    };
  }
}

class Pollutions {
  final Map<String, Measurement> measurements;
  final Station station;

  Pollutions({this.measurements, this.station});

  factory Pollutions.fromJson(Map<String, dynamic> json) {
    return Pollutions(
      measurements:
          _toObjectMap(json['measurements'], (e) => Measurement.fromJson(e)),
      station: _toObject(json['station'], (e) => Station.fromJson(e)),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'measurements': _fromMap(measurements, (e) => e.toJson()),
      'station': station?.toJson(),
    };
  }
}

class Station {
  final String city;
  final String latitude;
  final String longitude;
  final String name;

  Station({this.city, this.latitude, this.longitude, this.name});

  factory Station.fromJson(Map<String, dynamic> json) {
    return Station(
      city: json['city'] as String,
      latitude: json['latitude'] as String,
      longitude: json['longitude'] as String,
      name: json['name'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'city': city,
      'latitude': latitude,
      'longitude': longitude,
      'name': name,
    };
  }
}

Map<K, V> _fromMap<K, V>(data, V Function(dynamic) toJson) {
  if (data == null) {
    return null;
  }
  var result = <K, V>{};
  for (var key in data.keys) {
    V value;
    var element = data[key];
    if (element != null) {
      value = toJson(element);
    }
    result[key as K] = value;
  }
  return result;
}

double _toDouble(data) {
  if (data == null) {
    return null;
  }
  if (data is int) {
    return data.toDouble();
  }
  return data as double;
}

T _toObject<T>(data, T Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  return fromJson(data as Map<String, dynamic>);
}

Map<K, V> _toObjectMap<K, V>(data, V Function(Map<String, dynamic>) fromJson) {
  if (data == null) {
    return null;
  }
  var result = <K, V>{};
  for (var key in data.keys) {
    V value;
    var element = data[key];
    if (element != null) {
      value = fromJson(element as Map<String, dynamic>);
    }
    result[key as K] = value;
  }
  return result;
}

/*
Pollutions:
  "measurements": Map<String, Measurement>
  "station": Station


Measurement:
  "name": String
  "value": double
  "unit": String

Station:
  "city": String
  "name": String
  "latitude": String
  "longitude": String
*/

答案 3 :(得分:-1)

Map<String, dynamic> data = jsonDecode(yourVariable);