简体   繁体   English

如何在flutter dart中访问JSON嵌套数据

[英]How to access JSON nested data in flutter dart

  • I have the below json data, wherein I want to access the values inside the feeling_percentage .我有以下 json 数据,其中我想访问feeling_percentage中的值。
{
    "status": "200",
    "data": {
        "feeling_percentage": {
            "Happy": "0",
            "Sad": "0",
            "Energetic": "0",
            "Calm": "0",
            "Angry": "0",
            "Bored": "0"
        },
    }
}
  • I am able to fetch it using the below API code我可以使用下面的 API 代码来获取它
Future<List<Data>> makePostRequest() async {
  List<Data> list = [];
  final uri = Uri.parse('<api>');
  final headers = {'Content-Type': 'application/json', 'X-Api-Key':'<api_key>'};
  Map<String, dynamic> body = {'user_id': 3206161992, 'feeling_date': '15-04-2022'};
  String jsonBody = json.encode(body);
  final encoding = Encoding.getByName('utf-8');

  Response response = await post(
    uri,
    headers: headers,
    body: jsonBody,
    encoding: encoding,
  );

  int statusCode = response.statusCode;
  String responseBody = response.body;
  print('response body'+ responseBody);
}
  • After reading few articles, still not able to figure out how do I access the percentage of happy, sad inside the feeling_percentage.在阅读了几篇文章之后,仍然无法弄清楚我如何访问feeling_percentage 中的快乐、悲伤的百分比。
  • I have created the model as我已将模型创建为
class Data{
  FeelingPercentage feelingPercentage;

  Data(
      {required this.feelingPercentage});

  factory Data.fromJson(Map<String, dynamic> json) {
    return Data(
        feelingPercentage: FeelingPercentage.fromJson(json["data"]),
        );
  }
}

class FeelingPercentage {
  String? happy;
  String? sad;
  String? energetic;
  String? calm;
  String? angry;
  String? bored;

  FeelingPercentage({this.happy, this.sad, this.energetic, this.calm, this.angry, this.bored});

  factory FeelingPercentage.fromJson(Map<String, dynamic> json) {
    return FeelingPercentage(
      happy: json["happy"] as String,
      sad: json["sad"] as String,
      energetic: json["energetic"] as String,
      calm: json["calm"] as String,
      angry: json["angry"] as String,
      bored: json["bored"] as String,
    );
  }
}

You can use this website to convert your JSON object to a dart class.您可以使用网站将您的 JSON 对象转换为 dart 类。 it automatically creates the fromJson function, which can be used to pass JSON and receive the Dart objects.它会自动创建 fromJson 函数,该函数可用于传递 JSON 并接收 Dart 对象。

Change this line in your model feelingPercentage: FeelingPercentage.fromJson(json["data"]), to feelingPercentage: FeelingPercentage.fromJson(json["data"]["feeling_percentage"]),将模型中的这一行更改feelingPercentage: FeelingPercentage.fromJson(json["data"]), to feelingPercentage: FeelingPercentage.fromJson(json["data"]["feeling_percentage"]),

This will fix your issue.这将解决您的问题。

You can do a JSON decode that will will result in a map, and then do the assigned like you are doing on your from Json factory, but as another constructor instead:您可以执行将生成地图的 JSON 解码,然后像在from Json工厂中所做的那样进行分配,但作为另一个构造函数:

Class班级

Todo.fromMap(Map map) :
    this.title = map['title'],
    this.completed = map['completed'];

In use正在使用

Todo.fromMap(json.decode(item))

First decode response.body , then create FeelingPercentage object from json["data"]["feeling_percentage"] map.首先解码response.body ,然后从json["data"]["feeling_percentage"]映射创建FeelingPercentage对象。

Future<FeelingPercentage> makePostRequest() async {
...
  final json = json.decode(response.body);
  return FeelingPercentage.fromJson(json["data"]["feeling_percentage"])
}

class FeelingPercentage {
  String? happy;
  String? sad;
  String? energetic;
  String? calm;
  String? angry;
  String? bored;

  FeelingPercentage({this.happy, this.sad, this.energetic, this.calm, this.angry, this.bored});

  factory FeelingPercentage.fromJson(Map<String, dynamic> json) {
    return FeelingPercentage(
      happy: json["Happy"] as String,
      sad: json["Sad"] as String,
      energetic: json["Energetic"] as String,
      calm: json["Calm"] as String,
      angry: json["Angry"] as String,
      bored: json["Bored"] as String,
    );
  }
}

Another way:另一种方式:

import 'package:fast_json/fast_json_selector.dart' as parser;

void main() {
  final path = '{}.data.{}.feeling_percentage';
  final level = path.split('.').length;
  void select(parser.JsonSelectorEvent event) {
    final levels = event.levels;
    if (levels.length == level && levels.join('.') == path) {
      print(event.lastValue);
      event.lastValue = null;
    }
  }

  parser.parse(_source, select: select);
}

const _source = '''
{
    "status": "200",
    "data": {
        "feeling_percentage": {
            "Happy": "0",
            "Sad": "0",
            "Energetic": "0",
            "Calm": "0",
            "Angry": "0",
            "Bored": "0"
        }
    }
}''';

Output:输出:

{Happy: 0, Sad: 0, Energetic: 0, Calm: 0, Angry: 0, Bored: 0}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM